Python数据解析-css语法
CSS选择器
选择器 | 实例 | 释义 |
---|---|---|
.class | .intro | 选择class="intro"的所有元素 |
#id | #first-name | 选择id="first-name"的所有元素 |
* | * | 选择所有元素 |
element | p | 选择所有p元素 |
element,element | div,p | 选择所有div元素和p元素 |
element element | div p | 选择div元素内部的p元素 |
element>element | div>p | 选择父元素为div的所有p元素 |
[attribute] | [target] | 选择带有target属性的所有元素 |
[attribute=value] | [target=_blank] | 选择target="_blank"的所有元素 |
标签选择器
html、span、p、div等
import parsel
selector = parsel.Selector(html)
span = selector.css('span').getall()
print(span)
类选择器
它是通过为元素设置单独的class来赋予元素样式效果。
import parsel
selector = parsel.Selector(html)
p = selector.css('.top').getall()
print(p)
ID选择器
import parsel
selector = parsel.Selector(html)
p = selector.css('#content').getall()
print(p)
组合选择器
组合使用多个选择器
伪类选择器
语法 | 实例 | 释义 |
---|---|---|
:last-of-type | p:last-of-type | 选择每个p元素是其母元素最后一个p元素的p元素 |
:not(selector) | :not(p) | 选择所有p以外的元素 |
:nth-child(n) | p:nth-child(2) | 选择所有p元素的父元素的第二个子元素 |
:nth-last-child(n) | p:nth-last-child(2) | 选择所有p元素倒数的第二个子元素 |
属性提取器
import parsel
selector = parsel.Selector(html)
p = selector.css('p::text').getall()
print(p)
a = selector.css('a::attr(href)').getall()
print(a)