使用Nokogiri抓取数据:“未定义的方法`文本'”

时间:2013-12-11 06:49:27

标签: ruby-on-rails nokogiri

我在我的Rails应用程序中使用Nokogiri从网站上抓取信息但是我得到了:

NoMethodError: "undefined method `text' for nil:NilClass". 

这是示例代码:

require 'nokogiri'
require 'open-uri'  

url = "https://btc-e.com/exchange/btc_usd/"
doclink = Nokogiri::HTML(open(url))
doclink.at_css(".orderStats:nth-child(1) strong").text

我试图提取网址中列出的“最后价格”。我使用“SelectorGadget”Chrome加载项来查找CSS说明。我也尝试使用.orderStats strong但是没有方法错误。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您引用的页面使用JavaScript填充自身。由于Nokigiri没有执行JS,Nokigiri提取的页面非常无用:

<html>
<head><title>loading</title></head>
<body>
<p>Please wait...</p>
<script>/* POPULATES THE PAGE */</script>
</body>
</html>

一种解决方案是使用执行JS的刮刀,例如水豚+ PhantomJS。这是一篇描述如何:http://www.chrisle.me/2012/12/scraping-html5-sites-using-capybara-phantomjs/的文章。谷歌了解更多信息。