我正在使用 Nokogiri 读取本地 HTML 文档,如下所示:
f = File.open(local_xml)
@doc = Nokogiri::XML(f)
f.close
@doc
包含一个 Nokogiri XML 对象,我可以使用 at_css
对其进行解析。
我想用 Nokogiri 的 XML::Node 修改它,我绝对被困住了。我如何获取此 Nokogiri XML 文档并使用节点方法处理它?</p>
例如:
@doc.at_css('rates tr').add_next_sibling(element)
返回:
undefined method `add_next_sibling' for nil:NilClass (NoMethodError)
尽管 @doc.class
是 Nokogiri::XML::Document
。
为了完整起见,这是我要编辑的标记。
<html>
<head>
<title>Exchange Rates</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<table class="rates">
<tr>
<td class="up"><div></div></td>
<td class="date">Saturday, Jan 12</td>
<td class="rate up">3.83</td>
</tr>
<tr>
<td class="up"><div></div></td>
<td class="date">Friday, Jan 11</td>
<td class="rate up">3.70</td>
</tr>
<tr>
<td class="down"><div></div></td>
<td class="date">Thursday, Jan 10</td>
<td class="rate down">3.68</td>
</tr>
<tr>
<td class="down"><div></div></td>
<td class="date">Wedensday, Jan 9</td>
<td class="rate down">3.70</td>
</tr>
<tr>
<td class="up"><div></div></td>
<td class="date">Tuesday, Jan 8</td>
<td class="rate up">3.66</td>
</tr>
</table>
</body>
</html>
请您参考如下方法:
这是一个如何做你想做的事的例子。以 f
开头包含您要解析的 HTML 的缩短版本:
require 'nokogiri'
f = '
<html>
<head>
<title>Exchange Rates</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<table class="rates">
<tr>
<td class="up"><div></div></td>
<td class="date">Saturday, Jan 12</td>
<td class="rate up">3.83</td>
</tr>
</table>
</body>
</html>
'
doc = Nokogiri::HTML(f)
doc.at('.rates tr').add_next_sibling('<p>foobar</p>')
puts doc.to_html
您的代码错误地试图找到 class="rates"
<table>
的参数.在 CSS 中我们会使用 .rates
.使用 CSS 的另一种方法是 table[class="rates"]
.
您的示例没有定义您尝试添加到 HTML 的节点,因此我附加了 <p>foobar</p>
. Nokogiri 将允许您从头开始构建一个节点并附加它,或者使用标记并添加它,或者您可以从 HTML 中的一个位置找到一个节点,将其删除,然后将其插入其他位置。
该代码输出:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Exchange Rates</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<table class="rates">
<tr>
<td class="up"><div></div></td>
<td class="date">Saturday, Jan 12</td>
<td class="rate up">3.83</td>
</tr>
<p>foobar</p>
</table>
</body>
</html>
没有必要使用at_css
或 at_xpath
而不是 at
. Nokogiri 会感知您正在使用的访问器类型并进行处理。这同样适用于使用 xpath
或 css
而不是 search
.另外,at
相当于search('some accessor').first
, 所以它找到匹配节点的第一次出现。