0

I have not been able to search for a Node that has an HTML entity as a value.

I have this HTML fragment:

require 'nokogiri'

DATA = "<p>A paragraph <ul><li>Item 1</li><li>&#8853;</li><li>Mango</li></ul></p>"

doc = Nokogiri::HTML(DATA)

p doc.xpath('//li[contains(text(), "Man")]') => This returns a NodeSet
p doc.xpath('//li[contains(text(), "8853")]') => This returns 'Nil'

I am not able to figure out why the second statement returns NIL and how to fix it.

4

1 回答 1

7

当 Nokogiri 解析文档时,它会尝试解码实体,因此,您必须查找解码后的值:

require 'nokogiri'

data = "<p>A paragraph <ul><li>Item 1</li><li>&#8853;</li><li>Mango</li></ul></p>"

doc = Nokogiri::HTML(data)

p doc.search('li').map(&:text)
=> ["Item 1", "⊕", "Mango"]

请注意,HTML 实体已被解码为其真实字符。

puts doc.to_html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>A paragraph </p>
<ul>
<li>Item 1</li>
<li>⊕&lt;/li>
<li>Mango</li>
</ul>
</body></html>

同样,实体被解码。

p doc.xpath('//li[contains(text(), "⊕")]')
=> [#<Nokogiri::XML::Element:0x3fcd78d5f16c name="li" children=[#<Nokogiri::XML::Text:0x3fcd78d5ef64 "⊕">]>]
于 2013-02-15T12:52:11.463 回答