我正在尝试使用Hpricot解析HTML表格,但卡住了,无法从具有指定id的页面中选择表格元素。
这是我的ruby代码:
require 'rubygems'
require 'mechanize'
require 'hpricot'
agent = WWW::Mechanize.new
page = agent.get('http://www.indiapost.gov.in/pin/pinsearch.aspx')
form = page.forms.find {|f| f.name == 'form1'}
form.fields.find {|f| f.name == 'ddl_state'}.options[1].select
page = agent.submit(form, form.buttons[2])
doc = Hpricot(page.body)
puts doc.to_html # Here the doc contains the full HTML page
puts doc.search("//table[@id='gvw_offices']").first # This is NIL有没有人能帮我找出问题出在哪里。
发布于 2009-03-20 20:40:00
机械化将在内部使用hpricot (它是机械化的默认解析器)。更重要的是,它会将hpricot内容传递给解析器,所以你不必自己做:
require 'rubygems'
require 'mechanize'
#You don't really need this if you don't use hpricot directly
require 'hpricot'
agent = WWW::Mechanize.new
page = agent.get('http://www.indiapost.gov.in/pin/pinsearch.aspx')
form = page.forms.find {|f| f.name == 'form1'}
form.fields.find {|f| f.name == 'ddl_state'}.options[1].select
page = agent.submit(form, form.buttons[2])
puts page.parser.to_html # page.parser returns the hpricot parser
puts page.at("//table[@id='gvw_offices']") # This passes through to hpricot还要注意,page.search("foo").first等同于page.at("foo")。
发布于 2009-04-03 10:47:39
请注意,在以后的版本(0.9.0)中,默认情况下机械化不再使用Hpricot (它使用Nokogiri),您必须显式指定Hpricot才能继续使用:
WWW::Mechanize.html_parser = Hpricot就像这样,Hpricot周围没有引号或任何东西-可能有一个你可以为Hpricot指定的模块,因为如果你把这个语句放在你自己的模块声明中,它就不会工作。下面是在类的顶部(在打开模块或类之前)做这件事的最好方法
require 'mechanize'
require 'hpricot'
# Later versions of Mechanize no longer use Hpricot by default
# but have an attribute we can set to use it
begin
WWW::Mechanize.html_parser = Hpricot
rescue NoMethodError
# must be using an older version of Mechanize that doesn't
# have the html_parser attribute - just ignore it since
# this older version will use Hpricot anyway
end通过使用救援块,您可以确保如果他们有一个旧版本的机械化,它不会吐在不存在的html_parser属性上。(否则你需要让你的代码依赖于最新版本的机械化)
同样在最新版本中,WWW::Mechanize::List已被弃用。不要问我为什么,因为它完全破坏了语句的向后兼容性,比如
page.forms.name('form1').first这曾经是一种常见的习惯用法,因为Page#forms返回了一个机械化的列表,该列表有一个"name“方法。现在它返回一个简单的表单数组。
我花了很大力气才发现这一点,但你的用法是可行的,因为你使用的是find,这是一种数组方法。
但是,查找具有给定名称的第一个表单的更好方法是Page#form,因此表单查找行变成
form = page.form('form1')此方法适用于旧版本和新版本。
https://stackoverflow.com/questions/667697
复制相似问题