python - 在没有外部库的情况下将 CSS 选择器转换为 python 中的 XPath 选择器

标签 python css python-3.x xpath

是否可以转换复杂的 CSS 选择器,例如:

@[class="maintitle"] > .main-wrap #myid > .h1 bold

到 Python 3 中的 XPath 而不使用外部库?或者使用正则表达式?

我目前可以转换

@[class="maintitle"]

"//*[contains(@class,'maintitle')]" 但无法创建全局规则来转换这些更复杂的选择器。有可能吗?

编辑:我不能使用 cssselect。

最佳答案

尝试下面的 XPath

//*[@class="maintitle"]/*[contains(@class, "main-wrap")]//*[@id="myid"]/*[contains(@class="h1")]//bold

如果您需要可以将 CSS 转换为 XPath 的工具,可以尝试 lxml :

from cssselect import GenericTranslator
from lxml.etree import XPath

css_selector = """[class="maintitle"] > .main-wrap #myid > .h1 bold"""
print(XPath(GenericTranslator().css_to_xpath(css_selector)))

输出(看起来很奇怪,但是......):

descendant-or-self::*[@class = 'maintitle']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' main-wrap ')]/descendant-or-self::*/*[@id = 'myid']/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' h1 ')]/descendant-or-self::*/bold

请注意,您可能还需要在开头添加 // 作为:

print("//" + str(XPath(GenericTranslator().css_to_xpath(css_selector))))

关于python - 在没有外部库的情况下将 CSS 选择器转换为 python 中的 XPath 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47638137/

相关文章:

python - Scrapy不处理Xpath和CSS选择器中的TBODY

css - 是否可以在 CSS 中创建双边框?

python - Kubernetes Python 客户端 : update deployment spec with affinity

python - 比较运算符 < 和 > 如何将函数用作操作数?

python - 从 Python Pyramid 项目导出到 Excel .xlsx

具有后台工作线程的 Python Web 应用程序

php - 我发现的所有这些奇怪的代码是什么?

css - 在不使用 css 位置的情况下将 div 固定到底部

python - "periodically"在 Python 中替换字符串中字符的最佳方法是什么?

python - 是否可以根据 DataFrame 的值设置 float 的精度?