我在使用Nokogiri和XPATH嘗試從谷歌搜索結果中遇到問題。這只是谷歌,我有問題,其他網站似乎工作正常。用Nokogiri和XPATH抓取谷歌搜索結果的問題
我使用Chrome的元素檢查器獲取元素XPATH字符串。
這是一個工作堆棧溢出例如:
# Testing element on StackOverflow - returns the questions text
doc = Nokogiri::HTML(open('http://stackoverflow.com/questions/17763549/how-do-i-scrape-data-through-mechanize-and-nokogiri'))
p doc.at_xpath("//*[@id='question-header']/h1/a").text
=> "How do I scrape data through Mechanize and Nokogiri?"
在嘗試使用谷歌搜索結果:
# Testing element on Google, should return the first result title
doc = Nokogiri::HTML(open('https://www.google.com/#q=stack+overflow+error'))
p doc.at_xpath("//*[@id='rso']/li[1]/div/h3/a").text
NoMethodError: undefined method `text' for nil:NilClass
from (irb):81
from /home/kyle/.rvm/gems/ruby-2.1.0/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /home/kyle/.rvm/gems/ruby-2.1.0/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /home/kyle/.rvm/gems/ruby-2.1.0/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
我得到的所有谷歌頁面的 「NoMethodError」。任何想法這裏發生了什麼?
看起來您正在使用不會使用'open_uri'調用的異步搜索。將您的網址更改爲「https://www.google.com/search?q = stack + overflow + error''。 –
我嘗試過不使用這樣的網址 –
我能夠使用Mechanize和Nokogiri成功獲取URL和標題。 –