1. 程式人生 > >scrapy框架系列 (4) Scrapy Shell

scrapy框架系列 (4) Scrapy Shell

@class 元素 tid 之前 AR htm nbsp 招聘 cas

Scrapy Shell

Scrapy終端是一個交互終端,我們可以在未啟動spider的情況下嘗試及調試代碼,也可以用來測試XPath或CSS表達式,查看他們的工作方式,方便我們爬取的網頁中提取的數據。

如果安裝了 IPython ,Scrapy終端將使用 IPython (替代標準Python終端)。 IPython 終端與其他相比更為強大,提供智能的自動補全,高亮輸出,及其他特性。(推薦安裝IPython)

啟動Scrapy Shell

進入項目的根目錄,執行下列命令來啟動shell:

scrapy shell "http://www.itcast.cn/channel/teacher.shtml"

技術分享圖片

Scrapy Shell根據下載的頁面會自動創建一些方便使用的對象,例如 Response 對象,以及 Selector 對象 (對HTML及XML內容)

  • 當shell載入後,將得到一個包含response數據的本地 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 內置 XPath 和 CSS Selector 表達式機制

Selector有四個基本的方法,最常用的還是xpath:

  • xpath(): 傳入xpath表達式,返回該表達式所對應的所有節點的selector list列表
  • extract(): 序列化該節點為Unicode字符串並返回list
  • css(): 傳入CSS表達式,返回該表達式所對應的所有節點的selector list列表,語法同 BeautifulSoup4
  • re(): 根據傳入的正則表達式對數據進行提取,返回Unicode字符串list列表

XPath表達式的例子及對應的含義:

/html/head/title: 選擇<HTML>文檔中 <head> 標簽內的 <title> 元素
/html/head/title/text(): 選擇上面提到的 <title> 元素的文字
//td: 選擇所有的 <td> 元素
//div[@class="mine"]: 選擇所有具有 class="mine" 屬性的 div 元素

嘗試Selector

我們用騰訊社招的網站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-運營開發工程師(深圳)
職位名稱詳情頁:

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.io/zh_CN/latest/topics/shell.html

scrapy框架系列 (4) Scrapy Shell