grabbing text between two elements in nokogiri?

扶醉桌前 提交于 2019-12-04 11:25:40

Use:

/*/div[1]/following-sibling::text()[1]

This selects the first text-node sibling of the first div child of the top element of the document.

this returns the first text node within body between two div elements:

/body/text()[
     ./preceding::element()[1][local-name()="div"] and 
     ./following::element()[1][local-name()="div"]
][1]

should return

I NEED THIS TEXT ONLY

This XPath 1.0:

/body/text()[preceding-sibling::*[1][self::div]]
            [following-sibling::*[1][self::div]][1]

Also:

/body/text()[normalize-space()][1]

I don't have nokogiri, but here's an alternative using just basic string manipulation.

html=<<EOF
<body>
 <div>some text</div>
 I NEED THIS TEXT ONLY
 <div>some text</div>
 more text here
 <div>some text</div>
 one more text here
 <div>some text</div>
</body>
EOF
p html.split(/<\/*body>/)[1].split(/<\/div>/)[1].split(/<div>/)[0]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!