gpt4 book ai didi

python lxml xpath : how to get this predicate working

转载 作者:太空宇宙 更新时间:2023-11-03 20:33:21 24 4
gpt4 key购买 nike

早上好,

最近我把Python和网络抓取作为一种爱好......

我正在尝试解决 python lxml 和 xpath 谓词的问题,但是可惜 - 显然 stackoverflow 上没有类似的东西。所以我设法在下面的代码中重现,希望有人看到我没有看到的东西......

有人可以解释为什么 Result3 是一个空列表吗?我期望 Result3 与 Result1 相同。

如何实现 Result3 = Result1 ?

版本:AMD Windows 计算机上的 Python 3.7.3、lxml 4.4.0(使用 pip 安装,而不是 Christoph Gohlke 的二进制文件)。

提前致谢!

斯蒂芬

import lxml.html

simple_record = """<a href="some_map/some_file.png">dododo</a>"""
tree = lxml.html.fromstring(simple_record)

simple_xpath = "@href"
found_field = tree.xpath(simple_xpath)
print("Result1 = {}".format(found_field))

simple_xpath = """contains(@href,"some_file")"""
found_field = tree.xpath(simple_xpath)
print("Result2 = {}".format(found_field))

simple_xpath = """@href[contains(@href,"some_file")]"""
found_field = tree.xpath(simple_xpath)
print("Result3 = {}".format(found_field))

实际输出:

Result1 = ['some_map/some_file.png']
Result2 = True
Result3 = []

预期输出:

Result1 = ['some_map/some_file.png']
Result2 = True
Result3 = ['some_map/some_file.png']

最佳答案

第三个示例中的谓词 (@href[contains(@href,"some_file")]),翻译成英语意味着“在 simple_record 中查找一个节点,其中有一个属性href,它本身有一个属性href,它的属性值包含字符串some_file”。该节点不存在,因此返回空结果列表。

您想用英语问的是“在 simple_record 中查找一个节点,该节点具有属性 href,该属性的值包含字符串 some_file”(感谢@DanielHaley!)。翻译成xpath,你可以写成

simple_xpath   = '@href[contains(.,"some_file")]'

. 现在引用回由谓词过滤的上下文节点(即 @href 属性本身)。该表达式将导致结果 3 与结果 1 相同。

关于python lxml xpath : how to get this predicate working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57336720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com