【问题标题】:How do I scrape data through Mechanize and Nokogiri?如何通过 Mechanize 和 Nokogiri 抓取数据?
【发布时间】:2013-07-19 18:28:28
【问题描述】:

我正在开发一个从 http://www.screener.in/ 获取 HTML 的应用程序。

我可以输入像“Atul Auto Ltd”这样的公司名称并提交它,从the next page, 抓取以下详细信息:“CMP/BV”和“CMP”。

我正在使用此代码:

require 'mechanize'
require 'rubygems'
require 'nokogiri'

Company_name='Atul Auto Ltd.'
agent = Mechanize.new
page = agent.get('http://www.screener.in/')
form = agent.page.forms[0]
print agent.page.forms[0].fields
agent.page.forms[0]["q"]=Company_name
button = agent.page.forms[0].button_with(:value => "Search Company")
pages=agent.submit(form, button)
puts pages.at('.//*[@id="top"]/div[3]/div/table/tbody/tr/td[11]')
# not getting any output.

代码将我带到正确的页面,但我不知道如何查询以获取所需的数据。

我尝试了不同的方法,但没有成功。

如果可能的话,有人能指点我一个很好的教程,它解释了如何从 HTML 页面中抓取特定的类。 第一个“CMP/BV”的 XPath 是:

//*[@id="top"]/div[3]/div/table/tbody/tr/td[11]

但它没有给出任何输出。

【问题讨论】:

    标签: ruby nokogiri mechanize mechanize-ruby


    【解决方案1】:

    使用Nokogiri 我会如下:

    使用 CSS 选择器

    require 'nokogiri'
    require 'open-uri'
    
    doc = Nokogiri::HTML(open('http://www.screener.in/company/?q=Atul+Auto+Ltd.'))
    
    doc.class
    # => Nokogiri::HTML::Document
    doc.css('.table.draggable.table-striped.table-hover tr.strong td').class
    # => Nokogiri::XML::NodeSet
    
    row_data = doc.css('.table.draggable.table-striped.table-hover tr.strong td').map do |tdata|
      tdata.text
    end
    
     #From the webpage I took the below value from the table 
     #*Peer Comparison Top 7 companies in the same business*    
    
    row_data
    # => ["6.",
    #     "Atul Auto Ltd.",
    #     "193.45",
    #     "8.36",
    #     "216.66",
    #     "3.04",
    #     "7.56",
    #     "81.73",
    #     "96.91",
    #     "17.24",
    #     "2.92"]
    

    从网页中查看表格,我可以看到 CMP/BVCMP 分别是第十二列和第三列。现在我可以从数组row_data 中获取数据。所以 CMP 是第二个索引,CMP/BV 是数组 row_data 的最后一个值。

    row_data[2] # => "193.45" #CMP
    row_data.last # => "2.92" #CMP/BV
    

    使用 XPATH

    require 'nokogiri'
    require 'open-uri'
    
    doc = Nokogiri::HTML(open('http://www.screener.in/company/?q=Atul+Auto+Ltd.'))
    
    p doc.at_xpath("//*[@id='peers']/table/tbody/tr[6]/td[3]").text
    p doc.at_xpath("//*[@id='peers']/table/tbody/tr[6]/td[10]").text
    # >> "193.45" #CMP
    # >> "17.24"  #CMP/BV
    

    【讨论】:

    • 它有效你能告诉我,你是如何找到css选择器的? .我使用 chrome Developers tools 进行了跟踪,所以有没有任何工具可以做到这一点以及我如何使用 xpath 来做到这一点。
    • 我使用 firefox 插件 Firebug
    • 任何想法如何使用 xpath 来做到这一点。
    • CSS 并不总是最简单的选择器形式,但它们通常更易于阅读。有时您必须使用 XPath,因为它功能更全面。
    • @DeependerSingla 我通过在网页上查看源代码创建了xpath 表达式。我仍然建议您使用 CSS 选择器,因为您刚刚开始使用 Nokogiri。一旦你熟悉了 CSS 选择器,使用 .. 它会慢慢帮助你构建 xpath 表达式。我想说你也可以查看 Firefox 的 Firebug 插件。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多