Scrapy Shell
Scrapy終端是一個交互終端阔挠,我們可以在未啟動spider的情況下嘗試及調(diào)試代碼飘庄,也可以用來測試XPath或CSS表達式,查看他們的工作方式购撼,方便我們爬取的網(wǎng)頁中提取的數(shù)據(jù)跪削。
如果安裝了 IPython ,Scrapy終端將使用 IPython (替代標(biāo)準(zhǔn)Python終端)份招。 IPython 終端與其他相比更為強大切揭,提供智能的自動補全,高亮輸出锁摔,及其他特性。(推薦安裝IPython)
啟動Scrapy Shell
進入項目的根目錄哼审,執(zhí)行下列命令來啟動shell:
scrapy shell "http://www.itcast.cn/channel/teacher.shtml"
Scrapy Shell根據(jù)下載的頁面會自動創(chuàng)建一些方便使用的對象谐腰,例如 Response 對象孕豹,以及 Selector 對象 (對HTML及XML內(nèi)容)
。
當(dāng)shell載入后十气,將得到一個包含response數(shù)據(jù)的本地 response 變量励背,輸入
response.body
將輸出response的包體,輸出response.headers
可以看到response的包頭砸西。輸入
response.selector
時叶眉, 將獲取到一個response 初始化的類 Selector 的對象,此時可以通過使用response.selector.xpath()
或response.selector.css()
來對 response 進行查詢芹枷。Scrapy也提供了一些快捷方式, 例如
response.xpath()
或response.css()
同樣可以生效(如之前的案例)衅疙。
Selectors選擇器
Scrapy Selectors 內(nèi)置 XPath 和 CSS Selector 表達式機制
Selector有四個基本的方法,最常用的還是xpath:
- xpath(): 傳入xpath表達式鸳慈,返回該表達式所對應(yīng)的所有節(jié)點的selector list列表
- extract(): 序列化該節(jié)點為Unicode字符串并返回list
- css(): 傳入CSS表達式饱溢,返回該表達式所對應(yīng)的所有節(jié)點的selector list列表,語法同 BeautifulSoup4
- re(): 根據(jù)傳入的正則表達式對數(shù)據(jù)進行提取走芋,返回Unicode字符串list列表
XPath表達式的例子及對應(yīng)的含義:
/html/head/title: 選擇<HTML>文檔中 <head> 標(biāo)簽內(nèi)的 <title> 元素
/html/head/title/text(): 選擇上面提到的 <title> 元素的文字
//td: 選擇所有的 <td> 元素
//div[@class="mine"]: 選擇所有具有 class="mine" 屬性的 div 元素
嘗試Selector
我們用騰訊社招的網(wǎng)站http://hr.tencent.com/position.php?&start=0#a舉例:
# 啟動
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-運營開發(fā)工程師(深圳)
職位名稱詳情頁:
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]
技術(shù)類
以后做數(shù)據(jù)提取的時候,可以把現(xiàn)在Scrapy Shell中測試翁逞,測試通過后再應(yīng)用到代碼中肋杖。
當(dāng)然Scrapy Shell作用不僅僅如此,但是不屬于我們課程重點挖函,不做詳細介紹状植。
官方文檔:http://scrapy-chs.readthedocs.io/zh_CN/latest/topics/shell.html