在python中将CSS选择器转换为XPath选择器,而不使用外部库

2024-10-06 12:38:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

在python3中使用XPath而不使用外部库?还是用正则表达式?你知道吗

我现在可以转换

@[class="maintitle"]

但无法创建全局规则来转换这些更复杂的选择器。有可能吗?你知道吗

编辑:我不能使用cssselect。你知道吗


Tags: 编辑main规则选择器全局h1cssxpath
1条回答
网友
1楼 · 发布于 2024-10-06 12:38:22

在XPath下尝试

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

如果您需要可以将CSS转换为XPath的工具,可以尝试^{}

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))))

相关问题 更多 >