elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Resultado de busqueda de google en listview? vb.net
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Resultado de busqueda de google en listview? vb.net  (Leído 2,636 veces)
P4nd3m0n1um


Desconectado Desconectado

Mensajes: 1.419



Ver Perfil
Resultado de busqueda de google en listview? vb.net
« en: 21 Julio 2016, 20:38 pm »

Algo un poco extraño pero estaba buscando la manera de pasar los datos de una búsqueda de google a un listview, alguna idea?


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.817



Ver Perfil
Re: Resultado de busqueda de google en listview? vb.net
« Respuesta #1 en: 23 Julio 2016, 00:13 am »

Algo un poco extraño pero estaba buscando la manera de pasar los datos de una búsqueda de google a un listview, alguna idea?

Hola.

¿Podrías aclarar el siguiente detalle, por favor?:

A) Estás usando la API oficial de Google para .NET con un motor de búsqueda o 'Custom Search Engine' (CSE) mediante la API de 'Google Custom Search'.
B) Estás intentando desarrollar un algoritmo casero de búsqueda en Google.com para parsear manualmente el documento Html devuelto en la query.

Si no estás utilizando la API para .NET de Google, entonces debo advertirte de que lo que estás intentando hacer es algo prohibido en los términos legales (TOS) de Google, pero creo que podemos ignorar este detalle por que realmente Google es un servicio público y por mucho que digan en el TOS de Google esto no deja de ser ético y público, solo faltaria que nos quitasen la libertad de poder utilizar Google como nos de la real gana en nuestra aplicación...

El caso es que si no estás utilizando la API de Google Custom Search, la cual por cierto es de pago (si, para usar el motor de búsqueda de Google, hay que pagar), entonces va a ser un código muy tedioso de llevar a cabo, no solamente por el parsing manual, sino por que los servicios de Google están sujetos a cambios cada poco tiempo, así que con tiempo cambiarán algo y habrá que ir adaptando el código cada vez que hagan cambios que afecten a éste servicio...

¿Tienes parte del código ya hecha?



Bueno, al final me he animado a desarrollar una solución (casi)completa.

Requisitos:
  • VisualStudio 2015 (o adaptar la sintaxis a una versión anterior de VB.NET)
  • .NET Framework 4.5 para utilizar los métodos asincrónicos (o eliminar esos bloques de código en elcódigo fuente)
  • HtmlAgilityPack:https://htmlagilitypack.codeplex.com/

Aviso que no es perfecto y puede tener algunas limitaciones, pero funciona hasta donde lo he testeado.

Primero, una class para representar (algunos de) los parámetros de búsqueda de Google:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 22-July-2016
  4. ' ***********************************************************************
  5.  
  6. #Region " Imports "
  7. Imports System.Collections.Specialized
  8. #End Region
  9.  
  10. Namespace Google.Types
  11.  
  12.    ''' <summary>
  13.    ''' Represents the parameters of a query to <c>Google Search</c> service.
  14.    ''' </summary>
  15.    Public Class GoogleSearchOptions : Inherits Object
  16.  
  17. #Region " Constant Values "
  18.  
  19.        ''' <summary>
  20.        ''' The maximum number of results that can be included in the search results.
  21.        ''' </summary>
  22.        Protected ReadOnly maxNumberOfResults As Integer = 1000
  23.  
  24.        ''' <summary>
  25.        ''' The maximum search results that can be included to documents in the specified domain, host or web directory.
  26.        ''' </summary>
  27.        Protected ReadOnly maxWebsiteLength As Integer = 125
  28.  
  29. #End Region
  30.  
  31. #Region " Properties "
  32.  
  33.        ''' <summary>
  34.        ''' The search query. Words are separated by <c>+</c> signs.
  35.        ''' <para></para>
  36.        ''' Parameter name: <c>q</c>, Default value: N/A
  37.        ''' </summary>
  38.        ''' <remarks>
  39.        ''' See <see href="https://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/xml_reference/request_format.html#1076993"/> for additional query features.
  40.        ''' </remarks>
  41.        Public Overridable Property SearchTerm As String = ""
  42.  
  43.        ''' <summary>
  44.        ''' Restricts searches to pages in the specified language.
  45.        ''' If there are no results In the specified language, the search appliance displays results In all languages.
  46.        ''' <para></para>
  47.        ''' Parameter name: <c>lr</c>, Default value: Empty string
  48.        ''' </summary>
  49.        ''' <remarks>
  50.        ''' See <see href="https://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/xml_reference/request_format.html#1077312"/> for more information.
  51.        ''' </remarks>
  52.        Public Overridable Property Language As String = ""
  53.  
  54.        ''' <summary>
  55.        ''' Limits search results to documents in the specified domain, host or web directory.
  56.        ''' <para></para>
  57.        ''' The specified value must contain less than <c>125</c> characters.
  58.        ''' <para></para>
  59.        ''' Parameter name: <c>as_sitesearch</c>, Default value: Empty string
  60.        ''' </summary>
  61.        Public Overridable Property Website As String
  62.            <DebuggerNonUserCode>
  63.            Get
  64.                Return Me.websiteB
  65.            End Get
  66.            <DebuggerStepperBoundary>
  67.            Set(ByVal value As String)
  68.                If (value.Length > Me.maxWebsiteLength) Then
  69.                    value = value.Substring(0, Me.maxWebsiteLength)
  70.                End If
  71.                Me.websiteB = value
  72.            End Set
  73.        End Property
  74.  
  75.        ''' <summary>
  76.        ''' ( Backing field )
  77.        ''' Limits search results to documents in the specified domain, host or web directory.
  78.        ''' <para></para>
  79.        ''' The specified value must contain less than <c>125</c> characters.
  80.        ''' </summary>
  81.        Protected websiteB As String = ""
  82.  
  83.        ''' <summary>
  84.        ''' Include only files of the specified type in the search results.
  85.        ''' <para></para>
  86.        ''' Parameter name: <c>as_filetype</c>, Default value: Empty string
  87.        ''' </summary>
  88.        ''' <remarks>
  89.        ''' See <see href="https://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/xml_reference/request_format.html#1077199"/> for a list of possible values
  90.        ''' </remarks>
  91.        Public Overridable Property Filetype As String = ""
  92.  
  93.        ''' <summary>
  94.        ''' Sets the character encoding that is used to interpret the query string.
  95.        ''' <para></para>
  96.        ''' Parameter name: <c>ie</c>, Default value: <c>utf-8</c>
  97.        ''' </summary>
  98.        ''' <remarks>
  99.        ''' See <see href="https://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/xml_reference/request_format.html#1077479"/> for more information
  100.        ''' </remarks>
  101.        Public Overridable Property InputEncoding As Encoding = Encoding.GetEncoding("utf-8")
  102.  
  103.        ''' <summary>
  104.        ''' Sets the character encoding that is used to encode the results.
  105.        ''' <para></para>
  106.        ''' Parameter name: <c>oe</c>, Default value: <c>utf-8</c>
  107.        ''' </summary>
  108.        ''' <remarks>
  109.        ''' See <see href="https://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/xml_reference/request_format.html#1077479"/> for more information
  110.        ''' </remarks>
  111.        Public Overridable Property OutputEncoding As Encoding = Encoding.Default
  112.  
  113.        ''' <summary>
  114.        ''' The maximum number of results to include in the search results.
  115.        ''' <para></para>
  116.        ''' The maximum value of this parameter is 1000.
  117.        ''' <para></para>
  118.        ''' Parameter name: <c>num</c>, Default value: <c>10</c>
  119.        ''' </summary>
  120.        Public Overridable Property NumberOfResults As Integer
  121.            <DebuggerNonUserCode>
  122.            Get
  123.                Return Me.numberOfResultsB
  124.            End Get
  125.            <DebuggerStepperBoundary>
  126.            Set(ByVal value As Integer)
  127.                If (value < 0) Then
  128.                    value = 1
  129.                ElseIf (value > Me.maxNumberOfResults) Then
  130.                    value = Me.maxNumberOfResults
  131.                End If
  132.                Me.numberOfResultsB = value
  133.            End Set
  134.        End Property
  135.        ''' <summary>
  136.        ''' ( Backing field )
  137.        ''' The maximum number of results to include in the search results.
  138.        ''' <para></para>
  139.        ''' The maximum value of this parameter is 1000.
  140.        ''' </summary>
  141.        Protected numberOfResultsB As Integer = 10
  142.  
  143. #End Region
  144.  
  145. #Region " Constructors "
  146.        ''' <summary>
  147.        ''' Initializes a new instance of the <see cref="GoogleSearchOptions"/> class.
  148.        ''' </summary>
  149.        <DebuggerNonUserCode>
  150.        Public Sub New()
  151.        End Sub
  152. #End Region
  153.  
  154. #Region " Public Methods "
  155.  
  156.        ''' <summary>
  157.        ''' Returns a <see cref="NameValueCollection"/> that represents the <c>Google</c> query for this instance.
  158.        ''' </summary>
  159.        ''' <returns>
  160.        ''' A <see cref="NameValueCollection"/> that represents the <c>Google</c> query for this instance.
  161.        ''' </returns>
  162.        <DebuggerStepperBoundary>
  163.        Public Overridable Function ToNameValueCollection() As NameValueCollection
  164.  
  165.            Dim params As New NameValueCollection()
  166.            params.Add("q", HttpUtility.UrlEncode(Me.SearchTerm))
  167.  
  168.            If Not String.IsNullOrEmpty(Me.Filetype) Then
  169.                params.Add("as_filetype", Me.Filetype.ToLower())
  170.            End If
  171.  
  172.            If Not String.IsNullOrEmpty(Me.Website) Then
  173.                params.Add("as_sitesearch", Me.Website.ToLower())
  174.            End If
  175.  
  176.            If (Me.InputEncoding IsNot Nothing) Then
  177.                params.Add("ie", Me.InputEncoding.WebName.ToLower())
  178.            End If
  179.  
  180.            If (Me.OutputEncoding IsNot Nothing) Then
  181.                params.Add("oe", Me.OutputEncoding.WebName.ToLower())
  182.            End If
  183.  
  184.            If Not String.IsNullOrEmpty(Me.Language) Then
  185.                params.Add("lr", Me.Language.ToLower())
  186.            End If
  187.  
  188.            If (Me.NumberOfResults > 0) Then
  189.                params.Add("num", Me.NumberOfResults.ToString())
  190.            End If
  191.  
  192.            Return params
  193.  
  194.        End Function
  195.  
  196. #End Region
  197.  
  198. #Region " Operator Overrides "
  199.  
  200.        ''' <summary>
  201.        ''' Returns a <see cref="String"/> that represents the <c>Google</c> query for this instance.
  202.        ''' </summary>
  203.        ''' <returns>
  204.        ''' A <see cref="String"/> that represents the <c>Google</c> query for this instance.
  205.        ''' </returns>
  206.        <DebuggerStepperBoundary>
  207.        Public Overrides Function ToString() As String
  208.  
  209.            Dim url As String = "https://www.google.com/search?"
  210.            Dim params As NameValueCollection = Me.ToNameValueCollection()
  211.  
  212.            Dim sb As New StringBuilder
  213.            sb.Append(url)
  214.  
  215.            For Each key As String In params.AllKeys
  216.                sb.AppendFormat("{0}={1}&", key, params(key))
  217.            Next
  218.            sb.Remove((sb.Length - 1), 1)
  219.  
  220.            Return sb.ToString()
  221.  
  222.        End Function
  223.  
  224. #End Region
  225.  
  226.    End Class
  227.  
  228. End Namespace

Otra class para representar los resultados de búsqueda de Google:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 22-July-2016
  4. ' ***********************************************************************
  5.  
  6. Namespace Google.Types
  7.  
  8.    ''' <summary>
  9.    ''' Represents a <c>Google Search</c> result.
  10.    ''' </summary>
  11.    Public Class GoogleSearchResult : Inherits Object
  12.  
  13. #Region " Properties "
  14.  
  15.        ''' <summary>
  16.        ''' Gets the search result title.
  17.        ''' </summary>
  18.        ''' <value>
  19.        ''' The search result title.
  20.        ''' </value>
  21.        Public Overridable ReadOnly Property Title As String
  22.  
  23.        ''' <summary>
  24.        ''' Gets the search result title in the specified text encoding.
  25.        ''' </summary>
  26.        ''' <param name="inEnc">
  27.        ''' The source text encoding.
  28.        ''' </param>
  29.        '''
  30.        ''' <param name="outEnc">
  31.        ''' The target text encoding.
  32.        ''' </param>
  33.        ''' <value>
  34.        ''' The search result title in the specified text encoding.
  35.        ''' </value>
  36.        Public Overridable ReadOnly Property Title(ByVal inEnc As Encoding, ByVal outEnc As Encoding) As String
  37.            Get
  38.                Dim data As Byte() = inEnc.GetBytes(Me.Title)
  39.                Return outEnc.GetString(data)
  40.            End Get
  41.        End Property
  42.  
  43.        ''' <summary>
  44.        ''' Gets the search result description.
  45.        ''' </summary>
  46.        ''' <value>
  47.        ''' The search result description.
  48.        ''' </value>
  49.        Public Overridable ReadOnly Property Description As String
  50.  
  51.        ''' <summary>
  52.        ''' Gets the search result description in the specified text encoding.
  53.        ''' </summary>
  54.        ''' <param name="inEnc">
  55.        ''' The source text encoding.
  56.        ''' </param>
  57.        '''
  58.        ''' <param name="outEnc">
  59.        ''' The target text encoding.
  60.        ''' </param>
  61.        ''' <value>
  62.        ''' The search result description in the specified text encoding.
  63.        ''' </value>
  64.        Public Overridable ReadOnly Property Description(ByVal inEnc As Encoding, ByVal outEnc As Encoding) As String
  65.            Get
  66.                Dim data As Byte() = inEnc.GetBytes(Me.Description)
  67.                Return outEnc.GetString(data)
  68.            End Get
  69.        End Property
  70.  
  71.        ''' <summary>
  72.        ''' Gets the search result Url.
  73.        ''' </summary>
  74.        ''' <value>
  75.        ''' The search result Url.
  76.        ''' </value>
  77.        Public Overridable ReadOnly Property Url As String
  78.  
  79.        ''' <summary>
  80.        ''' Gets the search result <see cref="Uri"/>.
  81.        ''' </summary>
  82.        ''' <value>
  83.        ''' The search result <see cref="Uri"/>.
  84.        ''' </value>
  85.        Public Overridable ReadOnly Property Uri As Uri
  86.            <DebuggerStepperBoundary>
  87.            Get
  88.                Try
  89.                    Return New Uri(Me.Url)
  90.                Catch ex As UriFormatException ' ToDo: Add a proper custom exception handler.
  91.                    Throw
  92.                End Try
  93.            End Get
  94.        End Property
  95.  
  96. #End Region
  97.  
  98. #Region " Constructors "
  99.  
  100.        ''' <summary>
  101.        ''' Prevents a default instance of the <see cref="GoogleSearchResult"/> class from being created.
  102.        ''' </summary>
  103.        <DebuggerNonUserCode>
  104.        Private Sub New()
  105.        End Sub
  106.  
  107.        ''' <summary>
  108.        ''' Initializes a new instance of the <see cref="GoogleSearchResult"/> class.
  109.        ''' </summary>
  110.        ''' <param name="title">
  111.        ''' The search result title.
  112.        ''' </param>
  113.        '''
  114.        ''' <param name="url">
  115.        ''' The search result url.
  116.        ''' </param>
  117.        '''
  118.        ''' <param name="description">
  119.        ''' The search result description.
  120.        ''' </param>
  121.        <DebuggerStepperBoundary>
  122.        Public Sub New(ByVal title As String, ByVal url As String, ByVal description As String)
  123.            Me.Title = title
  124.            Me.Url = url
  125.            Me.Description = description
  126.        End Sub
  127.  
  128. #End Region
  129.  
  130.    End Class
  131.  
  132. End Namespace

Por último, esta class para buscar en Google y obtener los resultados de búsqueda:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 22-July-2016
  4. ' ***********************************************************************
  5.  
  6. #Region " Imports "
  7. Imports System.Threading.Thread
  8. Imports Google.Types
  9. Imports HtmlAgilityPack
  10. #End Region
  11.  
  12. Namespace Google.Tools
  13.  
  14.    ''' <summary>
  15.    ''' Searches the Worl Wide Web using <c>Google Search</c> service
  16.    ''' </summary>
  17.    Public NotInheritable Class GoogleSearcher : Inherits Object
  18.  
  19. #Region " Constructors "
  20.  
  21.        ''' <summary>
  22.        ''' Prevents a default instance of the <see cref="GoogleSearcher"/> class from being created.
  23.        ''' </summary>
  24.        Private Sub New()
  25.        End Sub
  26.  
  27. #End Region
  28.  
  29. #Region " Constant Values "
  30.  
  31.        ''' <summary>
  32.        ''' A fake agent to get the expected data to parse in the resulting html string response of <c>Google Search</c> requests.
  33.        ''' </summary>
  34.        Private Shared ReadOnly fakeAgent As String =
  35.            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"
  36.  
  37. #End Region
  38.  
  39. #Region " Public Methods "
  40.  
  41.        ''' <summary>
  42.        ''' Searches the Worl Wide Web using <c>Google Search</c> service with the specified search options.
  43.        ''' </summary>
  44.        ''' <param name="searchOptions">
  45.        ''' The search options to use with the <c>Google Search</c> service.
  46.        ''' </param>
  47.        ''' <param name="page">
  48.        ''' The search results page. Each page contains 100 results.
  49.        ''' <para></para>
  50.        ''' A search page contains 100 max. results. Note that max. total search results are 1000 (10 pages x 100 results).
  51.        ''' </param>
  52.        ''' <returns>
  53.        ''' The resulting response as a <c>Html</c> string.
  54.        ''' </returns>
  55.        <DebuggerStepperBoundary>
  56.        Public Shared Function GetSearchResultString(ByVal searchOptions As GoogleSearchOptions,
  57.                                                     ByVal page As Integer) As String
  58.  
  59.            If (page < 0) Then
  60.                Throw New ArgumentOutOfRangeException(paramName:="page")
  61.            End If
  62.  
  63.            If (searchOptions.NumberOfResults < 100) AndAlso (page > 0) Then
  64.                Return String.Empty
  65.            End If
  66.  
  67.            Using wc As New WebClient
  68.                wc.Headers.Add("user-agent", GoogleSearcher.fakeAgent)
  69.                Return wc.DownloadString(searchOptions.ToString() & String.Format("&start={0}", (100 * page)))
  70.            End Using
  71.  
  72.        End Function
  73.  
  74.        ''' <summary>
  75.        ''' Asynchronously searches the Worl Wide Web using <c>Google Search</c> service with the specified search options.
  76.        ''' </summary>
  77.        ''' <param name="searchOptions">
  78.        ''' The search options to use with the <c>Google Search</c> service.
  79.        ''' </param>
  80.        ''' <param name="page">
  81.        ''' The search results page.
  82.        ''' <para></para>
  83.        ''' A search page contains 100 max. results. Note that max. total search results are 1000 (10 pages x 100 results).
  84.        ''' </param>
  85.        ''' <returns>
  86.        ''' The resulting response as a <c>Html</c> string.
  87.        ''' </returns>
  88.        <DebuggerStepperBoundary>
  89.        Public Shared Async Function GetSearchResultStringAsync(ByVal searchOptions As GoogleSearchOptions,
  90.                                                                ByVal page As Integer) As Task(Of String)
  91.  
  92.            If (page < 0) Then
  93.                Throw New ArgumentOutOfRangeException(paramName:="page")
  94.            End If
  95.  
  96.            If (searchOptions.NumberOfResults < 100) AndAlso (page > 0) Then
  97.                Return String.Empty
  98.            End If
  99.  
  100.            Dim uri As New Uri(searchOptions.ToString() & String.Format("&start={0}", (100 * page)))
  101.  
  102.            Using wc As New WebClient
  103.                wc.Headers.Add("user-agent", GoogleSearcher.fakeAgent)
  104.                        Return Await wc.DownloadStringTaskAsync(searchOptions.ToString() & String.Format("&start={0}", (100 * page)))
  105.            End Using
  106.  
  107.        End Function
  108.  
  109.        ''' <summary>
  110.        ''' Searches the Worl Wide Web using <c>Google Search</c> service with the specified search options.
  111.        ''' </summary>
  112.        ''' <param name="searchOptions">
  113.        ''' The search options to use with the <c>Google Search</c> service.
  114.        ''' </param>
  115.        ''' <returns>
  116.        ''' A <see cref="List(Of GoogleSearchResult)"/> that represents the search results.
  117.        ''' </returns>
  118.        <DebuggerStepThrough>
  119.        Public Shared Function GetSearchResult(ByVal searchOptions As GoogleSearchOptions) As List(Of GoogleSearchResult)
  120.  
  121.            Dim html As String = GoogleSearcher.GetSearchResultString(searchOptions, page:=0)
  122.            Dim pageCount As Integer
  123.            Dim results As New List(Of GoogleSearchResult)
  124.  
  125.            Do While True
  126.  
  127.                If String.IsNullOrEmpty(html) Then ' No search-page to parse.
  128.                    Return results
  129.                End If
  130.  
  131.                ' Load the html document.
  132.                Dim doc As New HtmlDocument
  133.                doc.LoadHtml(html)
  134.  
  135.                ' Select the result nodes.
  136.                Dim nodes As HtmlNodeCollection
  137.                nodes = doc.DocumentNode.SelectNodes("//div[@class='g']")
  138.  
  139.                If (nodes Is Nothing) Then ' No search results in this page.
  140.                    Return results
  141.                End If
  142.  
  143.                ' Loop trough the nodes.
  144.                For Each node As HtmlAgilityPack.HtmlNode In nodes
  145.  
  146.                    Dim title As String = "Title unavailable."
  147.                    Dim description As String = "Description unavailable."
  148.                    Dim url As String = ""
  149.  
  150.                    Try
  151.                        title = HttpUtility.HtmlDecode(node.SelectSingleNode(".//div[@class='rc']/h3[@class='r']/a[@href]").InnerText)
  152.                    Catch ex As NullReferenceException
  153.                    End Try
  154.  
  155.                    Try
  156.                        description = HttpUtility.HtmlDecode(node.SelectSingleNode(".//div[@class='rc']/div[@class='s']/div[1]/span[@class='st']").InnerText)
  157.                    Catch ex As NullReferenceException
  158.                    End Try
  159.  
  160.                    Try
  161.                        url = HttpUtility.UrlDecode(node.SelectSingleNode(".//div[@class='rc']/h3[@class='r']/a[@href]").GetAttributeValue("href", "Unknown URL"))
  162.                    Catch ex As NullReferenceException
  163.                        Continue For
  164.                    End Try
  165.  
  166.                    results.Add(New GoogleSearchResult(title, url, description))
  167.                    If (results.Count = searchOptions.NumberOfResults) Then
  168.                        Exit Do
  169.                    End If
  170.                Next node
  171.  
  172.                Sleep(TimeSpan.FromSeconds(2))
  173.                html = GoogleSearcher.GetSearchResultString(searchOptions, Interlocked.Increment(pageCount))
  174.            Loop
  175.  
  176.            Return results
  177.  
  178.        End Function
  179.  
  180.        ''' <summary>
  181.        ''' Asynchronously searches the Worl Wide Web using <c>Google Search</c> service with the specified search options.
  182.        ''' </summary>
  183.        ''' <param name="searchOptions">
  184.        ''' The search options to use with the <c>Google Search</c> service.
  185.        ''' </param>
  186.        ''' <returns>
  187.        ''' A <see cref="List(Of GoogleSearchResult)"/> that represents the search results.
  188.        ''' </returns>
  189.        <DebuggerStepThrough>
  190.        Public Shared Async Function GetSearchResultAsync(ByVal searchOptions As GoogleSearchOptions) As Task(Of List(Of GoogleSearchResult))
  191.  
  192.            Dim html As String = Await GoogleSearcher.GetSearchResultStringAsync(searchOptions, page:=0)
  193.            Dim pageCount As Integer
  194.            Dim results As New List(Of GoogleSearchResult)
  195.  
  196.            Do While True
  197.  
  198.                If String.IsNullOrEmpty(html) Then ' No search-page to parse.
  199.                    Return results
  200.                End If
  201.  
  202.                ' Load the html document.
  203.                Dim doc As New HtmlDocument
  204.                doc.LoadHtml(html)
  205.  
  206.                ' Select the result nodes.
  207.                Dim nodes As HtmlNodeCollection
  208.                nodes = doc.DocumentNode.SelectNodes("//div[@class='g']")
  209.  
  210.                If (nodes Is Nothing) Then ' No search results in this page.
  211.                    Return results
  212.                End If
  213.  
  214.                ' Loop trough the nodes.
  215.                For Each node As HtmlAgilityPack.HtmlNode In nodes
  216.  
  217.                    Dim title As String = "Title unavailable."
  218.                    Dim description As String = "Description unavailable."
  219.                    Dim url As String = ""
  220.  
  221.                    Try
  222.                        title = HttpUtility.HtmlDecode(node.SelectSingleNode(".//div[@class='rc']/h3[@class='r']/a[@href]").InnerText)
  223.                    Catch ex As NullReferenceException
  224.                    End Try
  225.  
  226.                    Try
  227.                        description = HttpUtility.HtmlDecode(node.SelectSingleNode(".//div[@class='rc']/div[@class='s']/div[1]/span[@class='st']").InnerText)
  228.                    Catch ex As NullReferenceException
  229.                    End Try
  230.  
  231.                    Try
  232.                        url = HttpUtility.UrlDecode(node.SelectSingleNode(".//div[@class='rc']/h3[@class='r']/a[@href]").GetAttributeValue("href", "Unknown URL"))
  233.                    Catch ex As NullReferenceException
  234.                        Continue For
  235.                    End Try
  236.  
  237.                    results.Add(New GoogleSearchResult(title, url, description))
  238.                    If (results.Count = searchOptions.NumberOfResults) Then
  239.                        Exit Do
  240.                    End If
  241.                Next node
  242.  
  243.                Sleep(TimeSpan.FromSeconds(2))
  244.                html = GoogleSearcher.GetSearchResultString(searchOptions, Interlocked.Increment(pageCount))
  245.            Loop
  246.  
  247.            Return results
  248.  
  249.        End Function
  250.  
  251. #End Region
  252.  
  253.    End Class
  254.  
  255. End Namespace

Y aquí te dejo un ejemplo de uso:
Código
  1. Imports Google.Tools
  2. Imports Google.Types
  3.  
  4. Dim searchOptions As New GoogleSearchOptions
  5. With searchOptions
  6.    .SearchTerm = "elhacker.net"
  7.    .Language = "lang_en"
  8.    .InputEncoding = Encoding.GetEncoding("utf-8")
  9.    .OutputEncoding = Encoding.GetEncoding("Windows-1252")
  10.    .NumberOfResults = 100
  11. End With
  12.  
  13. Dim searchResults As List(Of GoogleSearchResult) = GoogleSearcher.GetSearchResult(searchOptions)
  14. Dim resultCount As Integer
  15.  
  16. For Each result As GoogleSearchResult In searchResults
  17.    Console.WriteLine("[{0:00}]", Interlocked.Increment(resultCount))
  18.    Console.WriteLine("Title: {0}", result.Title)
  19.    Console.WriteLine("Desc.: {0}", result.Description)
  20.    Console.WriteLine("Url..: {0}", result.Url)
  21.    Console.WriteLine()
  22. Next result
  23.  
  24. Console.WriteLine("Finished.")

Resultado de ejecución:
Código:
[01]
Title: WarZone - elhacker.NET
Desc.: WarZone 1.0. el wargame de elhacker.net. WarZone es un wargame que contiene una serie de pruebas con simulaciones de vulnerabilidades web, pruebas de ...
Url..: http://warzone.elhacker.net/

[02]
Title: Blog elhacker.NET
Desc.: Una red masiva de cámaras de CCTV se pueden utilizar para realizar ataques DDoS a ordenadores de todo el mundo. Circuito cerrado de televisión o CCTV ...
Url..: http://blog.elhacker.net/

[03]
Title: elhacker.INFO
Desc.: 579 Gbps, nuevo récord de transferencia de datos en un ataque DDoS xx Consiguen saltarse los controles de seguridad de Gmail “dividiendo” en dos una.. xx ...
Url..: http://ns2.elhacker.net/

[04]
Title: elhacker.NET (@elhackernet) | Twitter
Desc.: 17.9K tweets • 13 photos/videos • 22.6K followers. "Varios usuarios estarían vendiendo sus cuentas de Pokémon GO en eBay por ... https://t.co/orvE4fhiIA"
Url..: https://twitter.com/elhackernet

[05]
Title: elhacker.NET Youtube - YouTube
Desc.: Canal oficial de elhacker.NET. ... Copia Video - Ataque ddos al foro mas Noob de la red www elhacker net - Duration: 4 minutes, 47 seconds. 523 views; 1 year ...
Url..: https://www.youtube.com/user/elhackerdotnet

[06]
Title: elhacker.net | Facebook
Desc.: elhacker.net. 4455 Me gusta · 9 personas están hablando de esto. Visita nuestro grupo aqui: https://www.facebook.com/groups/elhackerdotnet/
Url..: https://es-es.facebook.com/elhacker.net

[07]
Title: ElHacker.net RSS – Windows Apps on Microsoft Store
Desc.: Obtene las ultimas noticias RSS y de Twitter de ElHacker.net! More. Get the app. Get the app · Get the app · Get the app. To use this app on your PC, upgrade to ...
Url..: https://www.microsoft.com/en-us/store/apps/elhackernet-rss/9nblgggzkps5

[08]
Title: http://elhacker.net - Prezi
Desc.: http://caca.com javascript://http://caca.com. Full transcript. More presentations by xxxxxxxx%22<" xxxx>%22" · Copia de Prezi Business Presentation Res.
Url..: https://prezi.com/clcwzhtsg6eu/httpelhackernet/

[09]

Title: elhacker.net.url and Other Malware Associated Files - Exterminate It!
Desc.: Want to know what kind of malware elhacker.net.url is associated with? Want to know how to get rid of elhacker.net.url?
Url..: http://www.exterminate-it.com/malpedia/file/elhacker.net.url

[10]
Title: Steam Community :: Group :: elhacker.NET
Desc.: Hola gente!! Elhacker.net ya dispone de un servidor de teamspeak para que lo uséis junto con los demás usuarios del grupo y foro. La dirección del servidor ...
Url..: https://steamcommunity.com/groups/elhackernet

etc...

Saludos


En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 756


Ver Perfil
Re: Resultado de busqueda de google en listview? vb.net
« Respuesta #2 en: 23 Julio 2016, 00:25 am »

No no no.... acaso darás tiempo de responder jajajajaja por dios...

Muy buena ya lo tengo guardado e interesante lo de que hay que pagarle a Google..

Salu2

PD: Pudiera hacerte una pregunta por un MP ¿?
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.817



Ver Perfil
Re: Resultado de busqueda de google en listview? vb.net
« Respuesta #3 en: 23 Julio 2016, 00:38 am »

PD: Pudiera hacerte una pregunta por un MP ¿?

Por supuesto, pero ten en cuenta si la respuesta a esa pregunta es sobre programación y pudiera ayudar a otras personas que tengan la misma duda, entonces quizás sería mejor si formulas la pregunta en un nuevo post.

Saludos!
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines