一、前言
scrapy shell也称"scrapy终端",是一个交互终端,用于未启动spider爬虫的情况下调试代码,方便对目标网页进行分析以及测试是否可以提取到页面数据
讲到提取数据就要先讲一讲scrapy内置的selector选择器了,selector选择器有如下几种常用用法:
1、xpath()或者css()
通过xpath表达式或者CSS表达式,返回该表达式所对应的所有节点的selector list列表
2、extract()或者extract_first()
extract()序列化该节点为Unicode字符串并返回list列表,而extract_first()只返回列表的第一项
3、re()
通过正则表达式对数据进行提取,返回Unicode字符串list列表
这里要特别强调一下selector选择器返回的都是列表
二、实际操作
1、启动终端
scrapy shell <url>
例如:scrapy shell https://cd.5i5j.com/zufang/

查看返回的response的响应状态,如果是200说明响应成功

有时由于网站有一些反爬的保护,导致响应状态不是200,可以通过增加user-agent参数来伪装浏览器
例如:scrapy shell -s USER_AGENT="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" https://cd.5i5j.com/zufang/
2、查看response信息
输入:response.headers可以看到response的包头

输入:response.headers['Set-Cookie']可以看到response某一个属性的值

输入:response.body可以看到response的包体

3、执行多行输入
当使用简单的多行输入命令后,单独Enter 键无法执行代码,需要使用shift+Enter键执行,如:
for i in response.headers:
print(i)

网上我也看到有的说用Ctrl + Enter 键执行,我不确定组合键是否和系统环境还有设置有关,可以这两个都试一下看自己是哪一个
4、response.xpath 实例
如要获取页面上房源的小区名,先利用F12自带的元素定位器,找到该元素的位置,再通过xpath表达式定位该元素

输入:response.selector.xpath('//div[@class="listX"]/p/a/text()')或者用快捷方式:response.xpath('//div[@class="listX"]/p/a/text()')获取该节点的selector list列表

目标元素为列表的第4项,可通过下标的方式获取,输入:response.xpath('//div[@class="listX"]/p/a/text()')[3]

上面获取的都是selector list列表,如果只想要得到data内容,输入:response.xpath('//div[@class="listX"]/p/a/text()').extract()

同样的,想要得到目标元素也可以通过下标的方式输入:response.xpath('//div[@class="listX"]/p/a/text()').extract()[3]

前面提到的extract_first()直接获取列表第一项,输入:response.xpath('//div[@class="listX"]/p/a/text()').extract_first()

5、退出终端模式
输入exit() 即可退出scrapy shell 终端模式
网友评论