【发布时间】:2011-11-17 18:05:58
【问题描述】:
我想在 google 上获取特定关键字搜索的所有搜索结果。我已经看到了刮擦的建议,但这似乎是个坏主意。我见过进行抓取和使用 API 的 Gems(我计划使用 ruby)。我还看到了使用 API 的建议。
有人知道现在最好的方法吗?该 API 不再受支持,我看到人们报告他们得到了不可用的数据。宝石是否有助于解决这个问题?
提前致谢。
【问题讨论】:
标签: ruby json gem google-search-api
我想在 google 上获取特定关键字搜索的所有搜索结果。我已经看到了刮擦的建议,但这似乎是个坏主意。我见过进行抓取和使用 API 的 Gems(我计划使用 ruby)。我还看到了使用 API 的建议。
有人知道现在最好的方法吗?该 API 不再受支持,我看到人们报告他们得到了不可用的数据。宝石是否有助于解决这个问题?
提前致谢。
【问题讨论】:
标签: ruby json gem google-search-api
我也选择了抓取选项,它比向谷歌询问密钥和加号更快,而且您每天的搜索查询不限于 100 个。正如理查德指出的那样,谷歌的 TOS 是一个问题。 这是我所做的一个对我有用的示例 - 如果您想通过代理进行连接,它也很有用:
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
【讨论】:
根据 http://code.google.com/apis/websearch/ ,搜索 API 已被弃用 - 但有一个替代品 Custom Search API。那会做你想要的吗?
如果是这样,一个快速的网络搜索出现了 https://github.com/alexreisner/google_custom_search ,以及其他宝石。
【讨论】:
使用 Google 自定义搜索 API:
【讨论】:
自定义搜索 API 很可能不是您想要的。我很确定您必须设置一个自定义搜索引擎,然后使用 API 进行查询,这只能搜索用户指定的一组域(即您不能执行一般的网络搜索)。
如果您需要执行一般的 Google 搜索,那么抓取是目前唯一的方法。编写 ruby 代码来执行 Google 搜索并抓取搜索结果 URL 非常容易(我自己是为一个暑期研究项目这样做的),但它确实违反了 Google 的 TOS,因此请注意。
【讨论】:
如果您在 google 搜索结果页面上运行爬虫,最终会出现 503 错误。一种更具可扩展性(和合法性)的方法是使用Google's Custom Search API。
该 API 每天免费提供 100 个搜索查询。如果您需要更多,可以在 Google Developers Console 中注册结算。额外请求每 1000 次查询收费 5 美元,每天最多 1 万次查询。
以下示例以 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")
【讨论】:
您也可以使用我们的API。我们负责抓取和解析 Google 搜索结果的困难部分。我们在 Ruby 中提供了如下简单的绑定:
query = GoogleSearchResults.new q: "coffee"
hash_results = query.get_hash
【讨论】: