我想替换 XHTML 文档中所有段落中的 inner_text。
我知道我可以像这样使用 Nokogiri 获取所有文本
doc.xpath("//text()")
但我只想对段落中的文本进行操作,如何在不影响链接中最终存在的 anchor 文本的情况下选择段落中的所有文本?
#For example : <p>some text <a href="/">This should not be changed</a> another one</p>
最佳答案
对于段落的直接子文本,使用//p/text()
irb> h = '<p>some text <a href="/">This should not be changed</a> another one</p>'
=> ...
irb> doc = Nokogiri::HTML(h)
=> ...
irb> doc.xpath '//p/text()'
=> [#<Nokogiri::XML::Text:0x80ac2e04 "some text ">, #<Nokogiri::XML::Text:0x80ac26c0 " another one">]
对于作为段落后代(直接或非直接)的文本,使用//p//text()。要排除那些将 anchor 作为父级的文本,您可以将它们减去。
irb> doc.xpath('//p//text()') - doc.xpath('//p//a/text()')
=> [#<Nokogiri::XML::Text:0x80ac2e04 "some text ">, #<Nokogiri::XML::Text:0x80ac26c0 " another one">]
可能有一种方法可以一次调用完成,但我的 xpath 知识还不够深入。
关于ruby - Nokogiri 在段落中查找文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2793624/