学习Python写爬虫的时候,遇到css定位问题,故小结一下css选择器定位的方式
通配符选择器:
* {color:red;}
CSS 类选择器
匹配所有class = ‘important’
*.important {color:red;}
去掉前面通配符也是一样的。
结合元素选择器
匹配所有p标签下class = ‘important’
p.important {color:red;}
CSS 多类选择器
匹配class = ‘important warning’,类名中存在空格分开的情况
.important.warning {background:silver;}
CSS ID 选择器
匹配所有id = ‘intro’
#intro {font-weight:bold;}
属性选择器
匹配所有属性是title
*[title] {color:red;}
匹配所有a标签下属性名是href
a[href] {color:red;}
多属性匹配
a[href][title] {color:red;}
XML文档也可以实行属性匹配器
planet[moons] {color:red;}
根据具体属性值选择
匹配a标签下href = ‘ ’
a[href="http://www.w3school.com.cn/about_us.asp"] {color: red;}
匹配多属性值的情况
a[href="http://www.w3school.com.cn/"][title="W3School"] {color: red;}
XML文档也可以实行‘属性 ’和 ‘值’ 进行匹配器
planet[moons="1"] {color: red;}
根据部分属性值选择
使用‘~’,匹配多个p标签下class名中含有‘important’
p[class~="important"] {color: red;}
子串匹配属性选择器
下表是对这些选择器的简单总结:
匹配a标签下,所有href 中,包含 ‘w3school.com.cn’的链接
a[href*="w3school.com.cn"] {color: red;}
特定属性选择类型
匹配所有lang属性下以‘en’或以‘en-’开头的所有元素,例如:‘en’,‘en-us’,‘en-au’,不适用‘enen’
*[lang|="en"] {color: red;}
CSS 选择器参考手册
后代选择器(descendant selector)又称为包含选择器。
匹配<h1>...<em>hello</em>...</h1>的所有元素,两个元素间隔可以是无限的
h1 em {color:red;}
选择子元素
只匹配<h1><em>hello</em></h1>的多有元素,两个元素间不能有间隔
h1 > strong {color:red;}
结合后代选择器和子选择器
匹配table标签下class = company,此类结构的所有元素
<table class = company>
<td>
<p>hello</p>
</td>
</table>
table.company td > p
选择相邻兄弟
匹配相同父标签下,h1和p的所有元素
h1 + p {margin-top:50px;}
注:h1和p必须由相同的父标签
结合其他选择器
html > body table + ul {margin-top:20px;}
CSS2 - :first-child 伪类
匹配第一个p标签或第一个li标签
p:first-child {font-weight: bold;}
li:first-child {text-transform:uppercase;}
匹配所有p标签下,第一个li标签
p > i:first-child{font-weight:bold;}
匹配第一个p标签下的所有li标签
p:first-child i{color:blue;}
更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。
如果你想用Python开辟副业赚钱,但不熟悉爬虫与反爬虫技术,没有接单途径,也缺乏兼职经验
关注下方微信公众号:Python编程学习圈,获取价值999元全套Python入门到进阶的学习资料以及教程,还有Python技术交流群一起交流学习哦。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!