是否可以转换复杂的 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/