Scrapy Shell
Scrapy終端是一個(gè)交互終端徒欣,我們可以在未啟動(dòng)spider的情況下嘗試及調(diào)試代碼饭望,也可以用來(lái)測(cè)試XPath或CSS表達(dá)式悔政,查看他們的工作方式,方便我們爬取的網(wǎng)頁(yè)中提取的數(shù)據(jù)庄蹋。
如果安裝了 IPython 瞬内,Scrapy終端將使用 IPython (替代標(biāo)準(zhǔn)Python終端)迷雪。 IPython 終端與其他相比更為強(qiáng)大,提供智能的自動(dòng)補(bǔ)全虫蝶,高亮輸出章咧,及其他特性。(推薦安裝IPython)
Scrapy Shell根據(jù)下載的頁(yè)面會(huì)自動(dòng)創(chuàng)建一些方便使用的對(duì)象能真,例如 Response 對(duì)象赁严,以及 Selector 對(duì)象 (對(duì)HTML及XML內(nèi)容)。
當(dāng)shell載入后粉铐,將得到一個(gè)包含response數(shù)據(jù)的本地 response 變量疼约,輸入 response.body將輸出response的包體,輸出 response.headers 可以看到response的包頭蝙泼。
輸入 response.selector 時(shí)程剥, 將獲取到一個(gè)response 初始化的類(lèi) Selector 的對(duì)象,此時(shí)可以通過(guò)使用 response.selector.xpath()或response.selector.css() 來(lái)對(duì) response 進(jìn)行查詢汤踏。
Scrapy也提供了一些快捷方式, 例如 response.xpath()或response.css()同樣可以生效织鲸。
Selectors選擇器
Scrapy Selectors 內(nèi)置 XPath 和 CSS Selector 表達(dá)式機(jī)制。
Selector有四個(gè)基本的方法溪胶,最常用的還是xpath:
xpath(): 傳入xpath表達(dá)式搂擦,返回該表達(dá)式所對(duì)應(yīng)的所有節(jié)點(diǎn)的selector list列表
extract(): 序列化該節(jié)點(diǎn)為Unicode字符串并返回list
css(): 傳入CSS表達(dá)式,返回該表達(dá)式所對(duì)應(yīng)的所有節(jié)點(diǎn)的selector list列表哗脖,語(yǔ)法同 BeautifulSoup4
re(): 根據(jù)傳入的正則表達(dá)式對(duì)數(shù)據(jù)進(jìn)行提取瀑踢,返回Unicode字符串list列表
使用案例:
# 啟動(dòng)
scrapy shell "http://hr.tencent.com/position.php?&start=0#a"
![Uploading scrapyshell1_605828.png . . .]
# 返回 xpath選擇器對(duì)象列表
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>']
# 打印列表第一個(gè)元素,終端編碼格式顯示
print response.xpath('//title').extract()[0]
<title>職位搜索 | 社會(huì)招聘 | Tencent 騰訊招聘</title>
# 返回 xpath選擇器對(duì)象列表
response.xpath('//title/text()')
<Selector xpath='//title/text()' data=u'\u804c\u4f4d\u641c\u7d22 | \u793e\u4f1a\u62db\u8058 | Tencent \u817e\u8baf\u62db\u8058'>
# 返回列表第一個(gè)元素的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()
職位搜索 | 社會(huì)招聘 | Tencent 騰訊招聘
response.xpath('//*[@class="even"]')
職位名稱(chēng):
print site[0].xpath('./td[1]/a/text()').extract()[0]
TEG15-運(yùn)營(yíng)開(kāi)發(fā)工程師(深圳)
職位名稱(chēng)詳情頁(yè):
print site[0].xpath('./td[1]/a/@href').extract()[0]
position_detail.php?id=20744&keywords=&tid=0&lid=0
職位類(lèi)別:
print site[0].xpath('./td[2]/text()').extract()[0]
技術(shù)類(lèi)