python - 使用 lxml.html 的 xpath 获取子元素 (Python)

标签 python html xpath lxml

我正在尝试使用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/

相关文章:

java - 在Java中使用xpath解析由多个xml文件组成的xml字符串

python - Python 中替代开关的性能差异

javascript - jQuery 点击功能不起作用

css - 为什么当元素 y 具有绝对位置时,另一个元素 y 下面的元素 x 向上移动

html - 如何正确放置 Bootstrap 导航栏

sql-server - 基于动态XML的插入/更新

python - 在 python 中初始化整数数组的最快方法是什么?

Python:将 csv 转换为 dict - 使用标题作为键

python - 使用 Mod_WSGI 和 Bottle 在 python 脚本初始化时只加载一次文件

php - 如何使用 php dom xpath 或正则表达式获取样式表 URL?