有没有人使用新的Google搜索API?

时间:2019-02-17 08:12:13

标签: vb.net

我尝试从Google获取图片搜索结果,并尝试了本教程。 https://hintdesk.com/2015/02/20/c-how-to-use-google-custom-search-api/

我也尝试了代码,但是看来这个例子比较旧,并且出现了一些错误。
错误在这一点上:

Dim customSearchService = New CustomsearchService(New BaseClientService.Initializer With {.ApiKey = apiKey})
     
Dim paging As IList(Of Result) = New List(Of Result)()

我正在努力完成这项工作,我的问题是是否有人对此有经验?

Imports GoogleSearchApi
Imports GoogleSearchApi.GoogleSearchClient
Imports GoogleSearchApi.GoogleSearchModel

Public Class Google
    Public Shared Sub Main(ByVal args As String())
        Const apiKey As String = "My API Key"
        Const searchEngineId As String = "My Search Engine ID"
        Const query As String = "hintdesk"

        Dim customSearchService = New CustomsearchService(New BaseClientService.Initializer With {.ApiKey = apiKey})
        Dim listRequest = customSearchService.Cse.List(query)

        listRequest.Cx = searchEngineId
        Console.WriteLine("Start...")
        Dim paging As IList(Of Result) = New List(Of Result)()
        Dim count = 0

        While paging IsNot Nothing
        Console.WriteLine($"Page {count}")
            listRequest.Start = count * 10 + 1
            paging = listRequest.Execute().Items

            If paging IsNot Nothing Then
                For Each item In paging
                    Console.WriteLine("Title : " & item.Title + Environment.NewLine & "Link : " + item.Link + Environment.NewLine + Environment.NewLine)
                Next
            End If

            count += 1
        End While

        Console.WriteLine("Done.")
        Console.ReadLine()
    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

现在,我使用此版本的代码从Google获得搜索结果。 唯一的问题是,现在我正努力使用JSON来获取数据。 在results数组中,似乎只得到了一些标题数据,而与搜索结果无关。

JSON对我来说是很新的东西,如果有人可以帮忙,那将是很棒的事情。

Public Shared Function Get_Google_Results(ByVal search As String) As Object

    Dim cx As String = "My custom search engine ID"
    Dim apiKey As String = "My API key"
    Dim request As WebRequest
    request = WebRequest.Create("https://www.googleapis.com/customsearch/v1?key=" & apiKey & "&cx=" & cx & "&q=" & search)
    Dim response As HttpWebResponse
    response = request.GetResponse()
    Dim dataStream As Stream
    dataStream = response.GetResponseStream
    Dim reader As New StreamReader(dataStream)
    Dim responseString As String = reader.ReadToEnd
    Dim jsonData
    jsonData = JsonConvert.DeserializeObject(responseString)

    Dim results As New List(Of String)

    For Each i In jsonData

        results.Add(New String(i.ToString))

    Next

    Return results

End Function