常用指令
創(chuàng)建項目
設置一個新的Scrapy項目芜飘。
scrapy startproject projectname
運行爬蟲
scrapy crawl spidername
數(shù)據(jù)提取測試
scrapy shell 'hhttp://www.xxx.com'
css選擇器
使用 shell
,您可以嘗試使用帶有 response
對象的 CSS
選擇元素:
>>> response.css('title')
[<Selector xpath='descendant-or-self::title' data='<title>Quotes to Scrape</title>'>]
要從上面的標題中提取文本,您可以:
>>> response.css('title::text').extract()
['Quotes to Scrape']
我們在CSS查詢中添加了 ::text
喘批,這意味著我們只想直接在 <title>
元素中選擇文本元素撩荣。如果我們不指定 ::text
,我們將獲得完整的 title
元素饶深,包括其標簽:
>>> response.css('title').extract()
['<title>Quotes to Scrape</title>']
可以使用 re
方法使用正則表達式進行提炔筒堋:
>>> response.css('title::text').re(r'Quotes.*')
['Quotes to Scrape']
>>> response.css('title::text').re(r'Q\w+')
['Quotes']
>>> response.css('title::text').re(r'(\w+) to (\w+)')
['Quotes', 'Scrape']
Xpath
Scrapy
選擇器還支持使用 XPath
表達式:
>>> response.xpath('//title')
[<Selector xpath='//title' data='<title>Quotes to Scrape</title>'>]
>>> response.xpath('//title/text()').extract_first()
'Quotes to Scrape'
數(shù)據(jù)存儲
Feed
存儲抓取數(shù)據(jù)的最簡單方法是使用 Feed 導出(Feed exports)
scrapy crawl spidername -o xxxx.json
這將生成一個 quotes.json
文件,其中包含所有被抓取的項目敌厘,以 JSON
序列化台猴。
使用其他格式,如JSON Lines
:
scrapy crawl spidername -o xxxx.jl
由于每條記錄都是單獨的行俱两,因此您可以處理大文件饱狂,而無需將所有內容都放在內存中
爬蟲參數(shù)
在運行爬蟲時,可以使用 -a
選項為您的爬蟲提供命令行參數(shù):
scrapy crawl spidername -o xxxx-humor.json -a tag=xxx
這些參數(shù)傳遞給 Spider 的 __init__
方法宪彩,默認成為spider屬性休讳。
您可以使用此方法使您的爬蟲根據(jù)參數(shù)構建 URL來實現(xiàn)僅抓取帶有特定tag的數(shù)據(jù):
def start_requests(self):
url = 'http://quotes.toscrape.com/'
tag = getattr(self, 'tag', None)
if tag is not None:
url = url + 'tag/' + tag
yield scrapy.Request(url, self.parse)