CSS选择器
单个类名首次匹配
soup.select_one('.stylelistrow')
比赛列表
soup.select('.stylelistrow')
复合类(即与另一个类别同时存在)
soup.select_one('.stylelistrow.otherclassname')
soup.select('.stylelistrow.otherclassname')
复合类名中的空格,例如class = stylelistrow otherclassname
,将被替换为“.”。您可以继续添加类。
类列表(或 - 匹配任何一个)
soup.select_one('.stylelistrow, .otherclassname')
soup.select('.stylelistrow, .otherclassname')
包含字符串(例如“stylelistrow”)的类属性:
以“style”开头:
[class^=style]
以 "row" 结尾
[class$=row]
包含“list”:
[class*=list]
^、$ 和 * 都是运算符。在此阅读更多: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
例如以锚点标签为例,如果你想要排除这个类,选择没有这个类的锚点标签:
a:not(.stylelistrow)
您可以在:not()伪类中传递简单、复合和复杂的CSS选择器列表。请参见https://facelessuser.github.io/soupsieve/selectors/pseudo-classes/#:not
bs4 4.7.1以上版本
包含特定字符串的innerText类
soup.select_one('.stylelistrow:contains("some string")')
soup.select('.stylelistrow:contains("some string")')
N.B.
soupsieve 2.1.0 + Dec'2020 onwards
新增:为避免与未来的CSS规范发生冲突,非标准伪类现在将以“:-soup-”前缀开头。
因此,:contains() 现在将被称为 :-soup-contains(),但是在一段时间内,仍将允许使用已弃用的 :contains() 形式,并警告用户迁移到 :-soup-contains()
新增:添加了一个新的非标准伪类 :-soup-contains-own(),其操作方式类似于 :-soup-contains(),但它只查看与当前作用域元素直接关联的文本节点,而不是其后代。
具有特定子元素(如a
标记)的特定类
soup.select_one('.stylelistrow:has(a)')
soup.select('.stylelistrow:has(a)')
<.. class="stylelistrow">
是匹配的,但<.. class="stylelistrow button">
不匹配。 - Wernightclass_
,可以正常工作。 - Wernightsoup.select("p.stylelistrow.another")
语法。这样可以精确匹配到类名为"stylelistrow"和"another"的标签,例如<p class="stylelistrow another yetAnother">
。 - smoothwaresoup.find_all("div", {"class": "stylelistrow"})
可以匹配精确的<.. class="stylelistrow">
和包含的<.. class="stylelistrow button">
。 - Girrafish