对于段落的直接子级文本,请使用//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()。要排除那些有锚定作为父级的文本,您只需减去它们即可。
irb> doc.xpath('//p//text()') - doc.xpath('//p//a/text()')
=> [#<Nokogiri::XML::Text:0x80ac2e04 "some text ">, #<Nokogiri::XML::Text:0x80ac26c0 " another one">]
可能有一种方法可以通过一个调用来完成,但是我的XPath知识并没有深入。