在Ruby中搜索/解析Google搜索结果

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

假设我拥有Google搜索结果页面的完整HTML。有没有人知道任何现有的代码(Ruby?)来搜索/解析Google搜索结果的第一页?理想情况下,它可以处理可在任何地方出现的购物结果和视频结果部分。

如果没有,一般来说,最好的基于Ruby的屏幕抓取工具是什么?

澄清一下:我知道以编程方式/ API方式获取Google搜索结果很困难/不可能而且简单地说CURLing结果页面存在很多问题。这里有关于stackoverflow的这两点的共识。我的问题不同。

ruby google-search google-search-api
6个回答
10
投票

这应该是非常简单的事情,看看由Ryan Bates演奏的Screen Scraping with ScrAPI屏幕。你仍然可以做到没有抓住libs,只是坚持像nokogiri这样的简单事情。

更新:

来自nokogiri的documentation

  require 'nokogiri'
  require 'open-uri'

  # Get a Nokogiri::HTML:Document for the page we’re interested in...

  doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))

  # Do funky things with it using Nokogiri::XML::Node methods...

  ####
  # Search for nodes by css
  doc.css('h3.r a.l').each do |link|
    puts link.content
  end

  ####
  # Search for nodes by xpath
  doc.xpath('//h3/a[@class="l"]').each do |link|
    puts link.content
  end

  ####
  # Or mix and match.
  doc.search('h3.r a.l', '//h3/a[@class="l"]').each do |link|
    puts link.content
  end

4
投票

我不清楚为什么你想要首先进行屏幕抓取。也许REST搜索API会更合适?它将以JSON格式返回结果,这将更容易解析,并节省带宽。例如,如果您的搜索是“foo bar”,则可以向http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=foo+bar发送GET请求并处理响应。

有关更多信息,请参阅此blog postofficial documentation


1
投票

我建议使用httparty + google ajax search api


0
投票

你应该能够用Mechanize轻松完成你的目标。

编辑:实际上,如果你已经有结果,你需要的只是HPricotNokogiri


0
投票

我不知道Ruby特定的代码,但这个google scraper可以帮助你。这是一个在线工具演示,可以搜索和解析Google搜索结果。最有趣的是那里的文章,解释了PHP中的解析过程,但它适用于Ruby和任何其他编程语言。


0
投票

随着谷歌不断变化,同时扩展结果的结构(丰富的片段,知识图,直接答案等),刮痧变得越来越难,我们建立了一个处理这种复杂性的部分服务,我们确实有一个Ruby library。它非常简单易用:

query = GoogleSearchResults.new q: "coffee"

# Parsed Google results into a Ruby hash
hash_results = query.get_hash
© www.soinside.com 2019 - 2024. All rights reserved.