参考链接:
Scrapy-document-selector
1. 打开shell界面,执行scrapy shell {your_crawl_url}
scrapy shell https://docs.scrapy.org/en/latest/_static/selectors-sample1.html
示例为Pycharm Terminal环境
如上scrapy shell示例返回完整Html(可通过response.text查看)如下:
<html>
<head>
<base href='http://example.com/' />
<title>Example website</title>
</head>
<body>
<div id='images'>
<a href='image1.html'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
<a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
<a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
<a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
<a href='image5.html'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
</div>
</body>
</html>
2. 在shell命令执行完后,会在shell中提供response变量,可直接通过response.css或response.xpath进行元素提取
示例命令
# 提取标题(提取第一个值)
response.css('title::text').get()
# 提取img元素的src属性(提取列表)
response.css('img::attr(src)').getall()
# css和xpath仍然返回SelectorList实例,可以继续调用css或xpath方法
# 如下先使用css选择器,后在css选择器选择结果的基础上再使用xpath选择器
response.css('img').xpath('@src').getall()
# 提取img元素的src属性(提取第一个值)
response.css('img::attr(src)').get()
# 提取所有图片链接的文本内容(提取列表)
response.css('div#images a::text').getall()
response.css('div#images').xpath('//a//text()').getall()
执行结果