使用 xpath 捕获 python 中标签之间的状态

capturing states between tags in python using xpath

我想按以下格式捕获单词 WORD 句子 This is what I want.:

<div id="message1">
<div class="message2">
<strong>WORD</strong> This is what I want.<br/>
</div>              
</div>

我试过的是:

import requests
from lxml import html
cont=session.get('http://mywebsite.com').content
tree=html.fromstring(cont)
word=tree.xpath('//div[@class="message2"]/strong')
sentence=tree.xpath('//div[@class="message2"]/br')
print word
print sentence

没有为我打印任何内容!

我发现 xpath helper 非常适合解决此类问题

word = tree.xpath('//div[@class="message2"]/strong/text()')[0]
sentence = tree.xpath('//div[@class="message2"]/strong/following-sibling::text()[1]')[0]

我不确定 LXML 的具体情况,但如果这是您要查找的文本,则调用文本不会 return 存在于强标记内的子树文本。

所以在一般的 XPath 术语中,这就是您要查找的仅匹配该文本的内容。

//*[@class="message2"]/text()

这就是你想要的:)

from lxml import html

text = """ 
<div id="message1">
<div class="message2">
<strong>WORD</strong> This is what I want.<br/>
</div>              
</div>
"""

tree = html.fromstring(text);
print(tree.xpath("//div[@class='message2']/strong/following-sibling::text()")[0])