获取谷歌搜索结果的正确方法是什么?

问题描述 投票:7回答:6

我想在谷歌上获取特定关键字搜索的所有搜索结果。我已经看到了刮痧的建议,但这似乎是一个坏主意。我见过Gems(我计划使用ruby),它会刮掉并使用API​​。我也看到了使用API​​的建议。

有谁知道现在最好的方法吗? API不再受支持,我看到有人报告说他们无法获得无法使用的数据。宝石是帮助解决这个问题还是不解决?

提前致谢。

ruby json gem google-search-api
6个回答
2
投票

根据http://code.google.com/apis/websearch/的说法,Search API已被弃用 - 但有一个替代品,Custom Search API。那会做你想要的吗?

如果是这样,快速网络搜索出现了https://github.com/alexreisner/google_custom_search,以及其他宝石。


10
投票

我也选择了scrape选项,它比谷歌要求密钥和加号更快,而且你不仅限于每天100次搜索查询。正如理查德指出的那样,Google的服务条款是一个问题。这是我做过的一个例子,对我来说很有用 - 如果你想通过代理连接它也很有用:

require 'rubygems'
require 'mechanize'

agent = Mechanize.new
agent.set_proxy '78.186.178.153', 8080
page = agent.get('http://www.google.com/')

google_form = page.form('f')
google_form.q = 'new york city council'

page = agent.submit(google_form, google_form.buttons.first)

page.links.each do |link|
    if link.href.to_s =~/url.q/
        str=link.href.to_s
        strList=str.split(%r{=|&}) 
        url=strList[1] 
        puts url
    end 
end

2
投票

2
投票

如果您在谷歌搜索结果页面上运行刮刀,最终会出现503错误。更具可扩展性(合法)的方法是使用Google's Custom Search API

API每天免费提供100个搜索查询。如果您需要更多,可以在Google Developers Console中注册结算。额外请求每1000次查询需要花费5美元,每天最多10k次查询。

以下示例以JSON格式获取Google搜索结果:

require 'open-uri'
require 'httparty'
require 'pp'

def get_google_search_results(search_phrase)
  # assign api key
  api_key = "Your api key here"

  # encode search phrase
  search_phrase_encoded = URI::encode(search_phrase)

  # get api response 
  response = HTTParty.get("https://www.googleapis.com/customsearch/v1?q=#{search_phrase_encoded}&key=#{api_key}&num=100")

  # pretty print api response
  pp response

  # get the url of the first search result
  first_search_result_link = response["items"][0]["link"]

end

get_google_search_results("Top Movies in Theatres")

1
投票

自定义搜索API很可能不是您正在寻找的。我很确定你必须设置一个自定义搜索引擎,你使用API​​来查询,这只能搜索用户指定的一组域(即你不能执行一般的网络搜索)。

如果您需要执行常规Google搜索,那么抓取是目前唯一的方法。编写ruby代码以执行Google搜索并刮取搜索结果URL(我自己为夏季研究项目做了这一点)非常容易,但它确实违反了Google的TOS,因此请注意。


1
投票

您也可以使用我们的API。我们负责处理报废和解析Google搜索结果的难点。我们在Ruby中提供的绑定非常简单:

query = GoogleSearchResults.new q: "coffee"
hash_results = query.get_hash

存储库:https://github.com/serpapi/google-search-results-ruby

© www.soinside.com 2019 - 2024. All rights reserved.