我想在“拼写检查”部分中刮一些Google搜索页面。
例如,如果我搜索“ cardiovascular diesese
”,它将链接到
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=cardiovascular%20diesese
我想刮掉“ Search instead for cardiovascular diesese
”部分。
如何使用Nokogiri和XPath?
require 'nokogiri'
require 'open-uri'
doc = Nokogiri::HTML(open("https://www.google.com/search?q=cardiovascular+diesese"))
doc.xpath("string(//span[@class='spell_orig']/a)") # => "cardiovascular diesese"
[如果您可以呈现JavaScript并需要使用原始示例URL,则在将文档加载到Nokogiri中(在Chrome中用$x
测试过后,此XPath选择器应该可以使用:
doc.xpath("//a[@class='spell_orig'][boolean(@href)]/text()") # => "cardiovascular diesese"