繁体   English   中英

python lxml xpath:如何使此谓词正常工作

[英]python lxml xpath: how to get this predicate working

早上好,

最近,我将python和网络抓取作为一种爱好...

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

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

如何获得Result3 = Result1?

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

提前致谢!

斯蒂夫

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 ,该属性href的属性值包含字符串some_file “。 该节点不存在,因此返回空结果列表。

用英语想问的是“在simple_record找到一个具有属性href的节点,该属性的值包含字符串some_file ”(谢谢@DanielHaley!)。 转换为xpath,您可以将其写为

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM