我正在尝试使用lxml.html获取子元素,代码如下。
import lxml.html as LH
html = """
<ul class="news-list2">
<li>
<div class="txt-box">
<p class="info">Number:<label>cewoilgas</label></p>
</div>
</li>
<li>
<div class="txt-box">
<p class="info">Number:<label>NHYQZX</label>
</p>
</div>
</li>
<li>
<div class="txt-box">
<p class="info">Number:<label>energyinfo</label>
</p>
</div>
</li>
<li>
<div class="txt-box">
<p class="info">Number:<label>calgary_information</label>
</p>
</div>
</li>
<li>
<div class="txt-box">
<p class="info">Number:<label>oilgas_pro</label>
</p>
</div>
</li>
</ul>
"""
获取li中的子元素:
htm = LH.fromstring(html)
for li in htm.xpath("//ul/li"):
print li.xpath("//p/label/text()")
好奇为什么结果是这样
['cewoilgas', 'NHYQZX', 'energyinfo', 'calgary_information', 'oilgas_pro']
['cewoilgas', 'NHYQZX', 'energyinfo', 'calgary_information', 'oilgas_pro']
['cewoilgas', 'NHYQZX', 'energyinfo', 'calgary_information', 'oilgas_pro']
['cewoilgas', 'NHYQZX', 'energyinfo', 'calgary_information', 'oilgas_pro']
['cewoilgas', 'NHYQZX', 'energyinfo', 'calgary_information', 'oilgas_pro']
我还发现解决方案是:
htm = LH.fromstring(html)
for li in htm.xpath("//ul/li"):
print li.xpath(".//p/label/text()")
结果是:
['cewoilgas']
['NHYQZX']
['energyinfo']
['calgary_information']
['oilgas_pro']
这应该被视为 lxml 的错误吗?为什么xpath在子元素(li)下时仍然匹配整个根元素(ul)?
最佳答案
不,这不是错误,而是预期行为。如果您的表达式以 //
开始,那么您在树的根部或树的任何元素上调用它都没有关系 - 它将是绝对的,并且它将是从根开始应用。
请记住,如果在某个元素上调用 xpath()
并且您希望它相对于该元素工作,请始终以引用当前节点的点开始表达式/em>.
顺便说一句,绝对(双关语)同样的情况发生在 selenium
中。它是 find_element(s)_by_xpath()
。
关于python - 使用 lxml.html 的 xpath 获取子元素 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41277891/