我正在学习如何使用Nokogiri,基于此代码,我遇到了几个问题:
require 'rubygems'
require 'mechanize'
post_agent = WWW::Mechanize.new
post_page = post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')
puts "\nabsolute path with tbody gives nil"
puts post_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div[2]').xpath('text()').to_s.strip.inspect
puts "\n.at_xpath gives an empty string"
puts post_page.parser.at_xpath("//div[@id='posts']/div/table/tr/td/div[2]").at_xpath('text()').to_s.strip.inspect
puts "\ntwo lines solution with .at_xpath gives an empty string"
rows = post_page.parser.xpath("//div[@id='posts']/div/table/tr/td/div[2]")
puts rows[0].at_xpath('text()').to_s.strip.inspect
puts
puts "two lines working code"
rows = post_page.parser.xpath("//div[@id='posts']/div/table/tr/td/div[2]")
puts rows[0].xpath('text()').to_s.strip
puts "\none line working code"
puts post_page.parser.xpath("//div[@id='posts']/div/table/tr/td/div[2]")[0].xpath('text()').to_s.strip
puts "\nanother one line code"
puts post_page.parser.at_xpath("//div[@id='posts']/div/table/tr/td/div[2]").xpath('text()').to_s.strip
puts "\none line code with full path"
puts post_page.parser.xpath("/html/body/div/div/div/div/div/table/tr/td/div[2]")[0].xpath('text()').to_s.strip
//
或/
更好吗? @AnthonyWJones说“使用不带前缀的//
”不是一个好主意。tbody
,否则我得到了nil
结果。如何从XPath删除元素以使事情正常进行?xpath
提取数据?at_xpath
起作用以提取数据?它在“ How do I parse an HTML table with Nokogiri?”中运行良好。有什么区别?//
意味着每个级别的每个节点,因此与/
相比,它要昂贵得多。*
用作占位符。text
方法。at_xpath
的示例。 我发现您经常使用text()
表达式。使用Nokogiri不需要此操作。您可以检索该节点,然后在该节点上调用text
方法。它便宜得多。
还要记住,Nokogiri支持CSS选择器。如果您使用的是HTML页面,它们可能会更容易。