我开始是:
text = "Dear Harry,<div>Hope all is well with you in the current strange times, and that you are not suffering too much in isolation.Look what I just got delivered:<img class=\"small\" src=\"s\"></div>"
我将其解析为Nokogiri片段:
f = Nokogiri::HTML::DocumentFragment.parse(text)
但是,以下两个都返回空列表:
f.xpath('//img')
f.xpath('img')
而且我不知道为什么。
但是,我可以找到这样的img标签:
f.xpath('*')[0] .xpath('img')
=> [#<Nokogiri::XML::Element:0x3fd63d7731cc name="img" attributes=[#<Nokogiri::XML::Attr:0x3fd63d772c68 name="class" value="small">, #<Nokogiri::XML::Attr:0x3fd63d772c54 name="src" value="s">]>]
我以为'// img'是要进行递归搜索的?
这似乎是一个未解决的问题,片段找不到具有预期xpath表达式的元素...
https://github.com/sparklemotion/nokogiri/issues/572
但是这会起作用...
f.xpath('.//img')
我大部分时候避免使用XPath。 CSS更具可读性,可用于我们所做的大多数事情:
require 'nokogiri'
text = 'foo<div>bar<img class="small" src="s"></div>'
fragment = Nokogiri::HTML::DocumentFragment.parse(text)
fragment.at('img').to_html
# => "<img class=\"small\" src=\"s\">"```