文章目录
Scrapy——CSS选择器
CSS即层叠式表,其选择器是一种用来确定HTML文档中某部分位置的语言
CSS选择器的语法比XPath更简单一些,但功能不如XPath强大。实际上,当我们调用Selector对象的CSS方法时,在其内部会使用Python库cssselect将CSS选择器表达式,然后调用Select对象的XPath方法
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
body = """
<html>
<head>
<base href = "http://www.baidu.com"/>
<title>CSS Selector</title>
</head>
<body>
<div id = 'images-1' style = "width:1230px;">
<a href = 'image1.html'>Name:Image 1<br/><img src = 'image1.jpg'/></a>
<a href = 'image2.html'>Name:Image 2<br/><img src = 'image2.jpg'/></a>
<a href = 'image3.html'>Name:Image 3<br/><img src = 'image3.jpg'/></a>
</div>
<div id = 'images-2' class = 'small'>
<a href = 'image4.html'>Name:Image 4<br/><img src = 'image4.jpg'/></a>
<a href = 'image5.html'>Name:Image 5<br/><img src = 'image5.jpg'/></a>
</div>
</body>
</html>
"""
response = HtmlResponse(url="http://www.example.com", body=body, encoding='utf-8')
E: 选中E元素
print(response.css('img')) # 选中所有img
E1, E2: 选中E1和E2元素
print(response.css('base, title')) # 选中base和title元素
E1 E2: 选中E1后代元素中的E2元素
print(response.css('div img')) # 选中div后代中的img
E1>E2: 选中E1子元素中的E2元素
print(response.css('body>div')) # 选中body子元素中的div
[ATTR]: 选中包含ATTR属性的元素
print(response.css('[style]')) #选中包含style属性的元素
print(response.css('[class]'))
print(response.css('[id]'))
print(response.css('[href]'))
[ATTR = VALUE]: 选中包含ATTR属性且值为VALUE的元素
print(response.css('[id = images-1]')) # 选中属性id值为images-1的元素
E:nth-child(n): 选中E 元素,且该元素必须是其父元素的第n 个子元素
print(response.css('a:nth-child(2)'))
print(response.css('div>a:nth-child(2)')) # 选中每个div的第二个a
print(response.css('div:nth-child(2)>a:nth-child(2)')) # 选中第二个div的第二个a
E:frist-child(n)选中E元素,该元素必须是其父元素的第一个子元素
E:last-child(n)选中E元素,该元素必须是其父元素的倒数第一个子元素
print(response.css('div:first-child>a:last-child'))#选中第一个div的最后一个a
选中E元素的文本
sel = response.css('a::text') # 选中a中的文本
print(sel)
print(sel.extract())
print(response.css('title::text').extract())
选中div节点中id属性的值
print(response.css("div::attr(id)"))