我正在尝试使用ruby xpath和nokogiri获取写在HTML表中的“cell4”值,如下所示:
<html>
<body>
<h1>Heading</h1>
<p>paragraph.</p>
<h4>Two rows and three columns:</h4>
<table border="0">
<tr>
<td>cell1</td>
<td>cell2</td>
</tr>
<tr>
<td>cell3</td>
<td>cell4</td>
</tr>
</table>
</body>
</html>
我有以下简单的代码,但它带来了[]。这个问题必须足够简单,但无法找到任何可以在谷歌上点击的内容
#!/usr/bin/ruby -w
require 'rubygems'
require 'nokogiri'
page1 = Nokogiri::HTML('test_simple.html')
a = page1.xpath("//html/body/table/tr[2]/td[2]")
p a
xpath在REXML上按预期工作,因此它是正确的,但不在nokogiri上。由于这将用于更大的htmls,因此无法使用REXML。问题似乎不仅仅是表格中只有其他标签内容
或者也不能被删除。
答案 0 :(得分:7)
恕我直言,使用Nokogiri中的CSS API(XPath总是让我感到头疼)是非常有用的:
page.css('td') # should return an array of 4 table cell nodes
page.css('td')[3] # return the 4th 'td' node, counting starts at 0
答案 1 :(得分:4)
感谢taro的评论,我能够通过一些努力解决问题
这是正确的代码:
#!/usr/bin/ruby -w
require 'rubygems'
require 'nokogiri'
page1 = Nokogiri::HTML(open('test_simple.html'))
a = page1.xpath("/html/body/table/tr[2]/td[2]").text
p a