【发布时间】:2010-01-22 19:46:35
【问题描述】:
我正在学习如何使用 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
- 在 XPath 中使用
//或/更好吗? @AnthonyWJones 表示“使用不带前缀的//”并不是一个好主意。 - 我必须从任何工作的 XPath 中删除
tbody,否则我会得到nil结果。如何从 XPath 中删除元素以使事情正常工作? - 如果不使用完整的 XPath,我是否必须使用两次
xpath来提取数据? - 为什么我不能让
at_xpath工作以提取数据?它在“How do I parse an HTML table with Nokogiri?”中运行良好。有什么区别?
【问题讨论】: