无法创建能够有条件地定位元素的 xpath
Trouble creating an xpath to be able to locate elements conditionally
我一直在尝试创建一个 xpath,应该在 p
元素内找到前三个 Yes
,直到 h1
元素内的文本 Demarcation
。我在下面的脚本中使用的现有脚本将所有文本定位在 p
元素中。但是,我找不到任何继续前进的想法。只需将我已经创建的那个视为占位符即可。
我如何创建一个 xapth 以便能够在 p
元素内定位前三个 Yes
而没有别的?
我目前的尝试:
from lxml.html import fromstring
htmldoc="""
<li>
<a>Nope</a>
<a>Nope</a>
<p>Yes</p>
<p>Yes</p>
<p>Yes</p>
<h1>Demarcation</h1>
<p>No</p>
<p>No</p>
<h1>Not this</h2>
<p>No</p>
<p>Not this</p>
</li>
"""
root = fromstring(htmldoc)
for item in root.xpath("//li/p"):
print(item.text)
在下面尝试select header "Demarcation"
兄弟姐妹之前的段落
//li/p[following-sibling::h1[.="Demarcation"]]
您似乎在尝试依赖包含 Demarcation
的 h1
标签,所以从它开始:
//h1[contains(., "Demarcation")]/preceding-sibling::p[contains(., "Yes")][position()<4]
我的想法是获取之前的 p
元素,我添加了 position()<4
所以你只得到三个,如果你只需要所有 p
可以删除它:
//h1[contains(., "Demarcation")]/preceding-sibling::p[contains(., "Yes")]
我一直在尝试创建一个 xpath,应该在 p
元素内找到前三个 Yes
,直到 h1
元素内的文本 Demarcation
。我在下面的脚本中使用的现有脚本将所有文本定位在 p
元素中。但是,我找不到任何继续前进的想法。只需将我已经创建的那个视为占位符即可。
我如何创建一个 xapth 以便能够在 p
元素内定位前三个 Yes
而没有别的?
我目前的尝试:
from lxml.html import fromstring
htmldoc="""
<li>
<a>Nope</a>
<a>Nope</a>
<p>Yes</p>
<p>Yes</p>
<p>Yes</p>
<h1>Demarcation</h1>
<p>No</p>
<p>No</p>
<h1>Not this</h2>
<p>No</p>
<p>Not this</p>
</li>
"""
root = fromstring(htmldoc)
for item in root.xpath("//li/p"):
print(item.text)
在下面尝试select header "Demarcation"
//li/p[following-sibling::h1[.="Demarcation"]]
您似乎在尝试依赖包含 Demarcation
的 h1
标签,所以从它开始:
//h1[contains(., "Demarcation")]/preceding-sibling::p[contains(., "Yes")][position()<4]
我的想法是获取之前的 p
元素,我添加了 position()<4
所以你只得到三个,如果你只需要所有 p
可以删除它:
//h1[contains(., "Demarcation")]/preceding-sibling::p[contains(., "Yes")]