如何在 Python 中使用 CSS 选择器

如何在 Python 中使用 CSS 选择器

在 Aspose.HTML FOSS for Python 中的选择器引擎按照标准特异性评估类、id、类型、属性和伪类选择器。本指南演示通过层叠进行选择器匹配——同样的引擎为 select() 和 element_matches() 提供支持——使用 pip 进行安装。

分步指南

步骤 1:安装软件包

git clone https://github.com/aspose-html-foss/Aspose.HTML-FOSS-for-Python.git
cd Aspose.HTML-FOSS-for-Python
pip install -e .

步骤 2:导入所需类

from aspose_html.dom import Document
from aspose_html.cssom import CSSStyleSheet

步骤 3:创建一个能够匹配多个选择器的元素

一个同时拥有 class 和 id 的元素会被 .foo、#bar 和 div 选择器同时匹配:

doc = Document()
el = doc.create_element("div")
el.set_attribute("class", "foo")
el.set_attribute("id", "bar")
doc.append_child(el)

第4步:让特异性决定

附加竞争规则 —— ID 选择器的 (1,0,0) 优于类选择器的 (0,1,0):

sheet = CSSStyleSheet()
sheet.replace_sync(".foo { color: red } #bar { color: blue }")
doc.attach_style_sheet(sheet)
print(el.get_computed_style().get_property_value("color"))

第5步:使用内联声明进行覆盖

内联声明具有 (1,0,0) 的内联级别优先级,且能胜过任何选择器特异性的作者规则:

inline = el.style
inline.set_property("color", "green")
print(el.get_computed_style().get_property_value("color"))

常见问题与解决方案

看起来正确的选择器匹配不到任何东西。 带有语法错误的选择器文本解析失败——引擎会报告错误而不是猜测;请检查选择器字符串。

:where() 的行为不同于 :is(). 这是设计如此: :where() 贡献零特异性, :is() 贡献其参数的特异性。

类型选择器意外地失效。 类型选择器拥有最低的特异性等级 (0,0,1);同一元素上的任何类或 id 规则都会覆盖它们。

常见问题

我可以在没有样式表的情况下运行选择器查询吗?

是的 — select() 直接对树进行选择器评估,element_matches() 则测试单个元素。

特异性是如何计算的?

specificity() 返回查询和层叠都使用的标准 (id, class, type) 元组。

哪些伪类已被建模?

针对 :is()、:where()、:has()、:not() 存在结构化表单,支持复杂参数,以及 nth-child 样式的结构选择器。

另请参阅

 中文