gpt4 book ai didi

python - Python 中的 XPATH 语法验证器

转载 作者:行者123 更新时间:2023-11-30 22:15:53 25 4
gpt4 key购买 nike

我开发了一个包含许多操作的爬虫。涉及许多 xpath,因此我使用 json 文件进行存储。然后爬虫开始运行我想对 xpath 进行基本语法检查(在使用 xpath 之前),并针对无效的 xpath 引发错误。

例如:

xpath1 = '//*[@id="react-root"]/section'
xpath2 = '//*[[@id="react-root"]/section'
xpath3 = '//*[@id="react-root"]\section'

在这些 xpath 中,只有 xpath1 有效

是否有任何模块或正则表达式可以进行这种验证?

最佳答案

您可以使用 lxml.etree.XPath 编译 xpath 字符串如果语法不正确,将会引发异常:

>>> import lxml.etree
>>> lxml.etree.XPath('//*[@id="react-root"]/section')
//*[@id="react-root"]/section
>>> lxml.etree.XPath('//*[[@id="react-root"]/section')
Traceback (most recent call last):
...
lxml.etree.XPathSyntaxError: Invalid expression
>>> lxml.etree.XPath(r'//*[@id="react-root"]\section')
Traceback (most recent call last):
...
lxml.etree.XPathSyntaxError: Invalid expression

关于python - Python 中的 XPATH 语法验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50151904/

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