Scrapy终端是一个交互终端,咱们能够在未启动spider的状况下尝试及调试代码,也能够用来测试XPath或CSS表达式,查看他们的工做方式,方便咱们爬取的网页中提取的数据。php
若是安装了 IPython ,Scrapy终端将使用 IPython (替代标准Python终端)。 IPython 终端与其余相比更为强大,提供智能的自动补全,高亮输出,及其余特性。(推荐安装IPython)css
进入项目的根目录,执行下列命令来启动shell:html
scrapy shell "http://www.itcast.cn/channel/teacher.shtml"
图片描述正则表达式
Scrapy Shell根据下载的页面会自动建立一些方便使用的对象,例如 Response 对象,以及 Selector 对象 (对HTML及XML内容)。shell
response.body
将输出response的包体,输出 response.headers
能够看到response的包头。response.selector
时, 将获取到一个response 初始化的类 Selector 的对象,此时能够经过使用response.selector.xpath()
或response.selector.css()
来对 response 进行查询。response.xpath()
或response.css()
一样能够生效(如以前的案例)。Scrapy Selectors 内置 XPath 和 CSS Selector 表达式机制scrapy
Selector有四个基本的方法,最经常使用的仍是xpath:ide
/html/head/title: 选择<HTML>文档中 <head> 标签内的 <title> 元素 /html/head/title/text(): 选择上面提到的 <title> 元素的文字 //td: 选择全部的 <td> 元素 //div[@class="mine"]: 选择全部具备 class="mine" 属性的 div 元素
咱们用腾讯社招的网站http://hr.tencent.com/positio...举例:测试
# 启动 scrapy shell "http://hr.tencent.com/position.php?&start=0#a" # 返回 xpath选择器对象列表 response.xpath('//title') [<Selector xpath='//title' data=u'<title>\u804c\u4f4d\u641c\u7d22 | \u793e\u4f1a\u62db\u8058 | Tencent \u817e\u8baf\u62db\u8058</title'>] # 使用 extract()方法返回 Unicode字符串列表 response.xpath('//title').extract() [u'<title>\u804c\u4f4d\u641c\u7d22 | \u793e\u4f1a\u62db\u8058 | Tencent \u817e\u8baf\u62db\u8058</title>'] # 打印列表第一个元素,终端编码格式显示 print response.xpath('//title').extract()[0] <title>职位搜索 | 社会招聘 | Tencent 腾讯招聘</title> # 返回 xpath选择器对象列表 response.xpath('//title/text()') <Selector xpath='//title/text()' data=u'\u804c\u4f4d\u641c\u7d22 | \u793e\u4f1a\u62db\u8058 | Tencent \u817e\u8baf\u62db\u8058'> # 返回列表第一个元素的Unicode字符串 response.xpath('//title/text()')[0].extract() u'\u804c\u4f4d\u641c\u7d22 | \u793e\u4f1a\u62db\u8058 | Tencent \u817e\u8baf\u62db\u8058' # 按终端编码格式显示 print response.xpath('//title/text()')[0].extract() 职位搜索 | 社会招聘 | Tencent 腾讯招聘 response.xpath('//*[@class="even"]') 职位名称: print site[0].xpath('./td[1]/a/text()').extract()[0] TEG15-运营开发工程师(深圳) 职位名称详情页: print site[0].xpath('./td[1]/a/@href').extract()[0] position_detail.php?id=20744&keywords=&tid=0&lid=0 职位类别: print site[0].xpath('./td[2]/text()').extract()[0] 技术类
之后作数据提取的时候,能够把如今Scrapy Shell中测试,测试经过后再应用到代码中。网站
固然Scrapy Shell做用不单单如此,可是不属于咱们课程重点,不作详细介绍。编码
官方文档:[http://scrapy-chs.readthedocs...Spider][3]