目錄
- 參考
- 概述
- 安裝
- 編寫scrapy程序
- 問題總結(jié)
1. 參考
- [1] docs.scrapy.org/en/latest/intro/tutorial
- [2] docs.scrapy.org/en/latest/intro/install
- [3] rwxwsblog/如何讓你的scrapy爬蟲不再被ban
- [4] 生無可戀的程序員/Python--Scrapy爬蟲獲取簡書作者ID的全部文章列表數(shù)據(jù)
- [5] liuhehe123/scrapy--解決css選擇器遇見含空格類提取問題response.css()
- [6] yamadeee/Scrapy Selector選擇器
- [7] stackoverflow/scraping the file with html saved in local system
- [8] runoob/Scrapy 入門教程
2. 概述
Scrapy 是用 Python 實現(xiàn)的一個為了爬取網(wǎng)站數(shù)據(jù)夯尽、提取結(jié)構(gòu)性數(shù)據(jù)而編寫的應(yīng)用框架。
Scrapy架構(gòu)圖(綠線是數(shù)據(jù)流向)
image
- Scrapy Engine(引擎): 負(fù)責(zé)Spider登馒、ItemPipeline匙握、Downloader、Scheduler中間的通訊陈轿,信號圈纺、數(shù)據(jù)傳遞等。
- Scheduler(調(diào)度器): 負(fù)責(zé)接受引擎發(fā)送過來的Request請求麦射,并按照一定的方式進行整理排列蛾娶,入隊,當(dāng)引擎需要時潜秋,交還給引擎蛔琅。
- Downloader(下載器):負(fù)責(zé)下載Scrapy Engine(引擎)發(fā)送的所有Requests請求,并將其獲取到的Responses交還給Scrapy Engine(引擎)峻呛,由引擎交給Spider來處理罗售,
- Spider(爬蟲):負(fù)責(zé)處理所有Responses,從中分析提取數(shù)據(jù)钩述,獲取Item字段需要的數(shù)據(jù)寨躁,并將需要跟進的URL提交給引擎,再次進入Scheduler(調(diào)度器)牙勘。
- Item Pipeline(管道):負(fù)責(zé)處理Spider中獲取到的Item职恳,并進行進行后期處理(詳細(xì)分析、過濾方面、存儲等)的地方话肖。
- Downloader Middlewares(下載中間件):可以當(dāng)作是一個可以自定義擴展下載功能的組件。
- Spider Middlewares(Spider中間件):可以理解為是一個可以自定擴展和操作引擎和Spider中間通信的功能組件(比如進入Spider的Responses;和從Spider出去的Requests)
3. 安裝
安裝依賴
apt-get install python-dev python-pip libxml2-dev libxslt1-dev zlib1g-dev libffi-dev libssl-dev
安裝scrapy
pip3 install Scrapy
4. 編寫scrapy程序
創(chuàng)建scrapy工程
scrapy startproject project_name
project_name/
scrapy.cfg # deploy configuration file
tutorial/ # project's Python module, you'll import your code from here
__init__.py
items.py # project items definition file
middlewares.py # project middlewares file
pipelines.py # project pipelines file
settings.py # project settings file
spiders/ # a directory where you'll later put your spiders
__init__.py
文件說明:
- scrapy.cfg:項目的配置信息葡幸,主要為Scrapy命令行工具提供一個基礎(chǔ)的配置信息最筒。(真正爬蟲相關(guān)的配置信息在settings.py文件中)
- items.py:設(shè)置數(shù)據(jù)存儲模板,用于結(jié)構(gòu)化數(shù)據(jù)蔚叨,如:Django的Model
- pipelines:數(shù)據(jù)處理行為床蜘,如:一般結(jié)構(gòu)化的數(shù)據(jù)持久化
- settings.py:配置文件,如:遞歸的層數(shù)蔑水、并發(fā)數(shù)邢锯,延遲下載等
- spiders:爬蟲目錄,如:創(chuàng)建文件搀别,編寫爬蟲規(guī)則
示例程序丹擎,放在spiders目錄
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
def start_requests(self):
urls = [
'http://quotes.toscrape.com/page/1/',
'http://quotes.toscrape.com/page/2/',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
page = response.url.split("/")[-2]
filename = 'quotes-%s.html' % page
with open(filename, 'wb') as f:
f.write(response.body)
self.log('Saved file %s' % filename)
QuotesSpider繼承于scrapy.Spider,并定義了一些屬性和方法:
- name: 標(biāo)識這個Spider。它在項目中必須是唯一的蒂培,也就是說再愈,不能為不同的Spiders設(shè)置相同的名稱。
- start_requests():必須返回一個可迭代的請求(可以返回一個請求列表或編寫一個生成器函數(shù))护戳,Spiders將開始從中爬行翎冲。后續(xù)請求將從這些初始請求中依次生成。
- parse():它將被調(diào)用來處理為每個請求下載的響應(yīng)媳荒。response參數(shù)是TextResponse的一個實例抗悍,它包含頁面內(nèi)容,并且有進一步有用的方法來處理它钳枕。parse()方法通常解析響應(yīng)缴渊,將抓取的數(shù)據(jù)提取為dict,并找到要跟蹤的新url鱼炒,并從中創(chuàng)建新的請求(請求)衔沼。
運行scrapy
scrapy crawl quotes
- 這個命令使用剛剛添加的名稱為quotes的運行Spider,它將發(fā)送對quotes.toscrape.com域名的一些請求田柔。會得到一個類似的輸出:
(omitted for brevity)
2016-12-16 21:24:05 [scrapy.core.engine] INFO: Spider opened
2016-12-16 21:24:05 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-12-16 21:24:05 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quotes.toscrape.com/robots.txt> (referer: None)
2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/1/> (referer: None)
2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/2/> (referer: None)
2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-1.html
2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-2.html
2016-12-16 21:24:05 [scrapy.core.engine] INFO: Closing spider (finished)`
檢查當(dāng)前目錄中的文件俐巴。應(yīng)該已經(jīng)創(chuàng)建了兩個新文件:quotes-1.html和quotes-2.html骨望,以及對應(yīng)url的內(nèi)容硬爆,正如我們的解析方法所指示的那樣。
可以使用Feed導(dǎo)出結(jié)果擎鸠,使用以下命令輸出為json格式數(shù)據(jù):
scrapy crawl quotes -o quotes.json
5. 問題總結(jié)
5.1 HTTP 403
解決方法:
在Settings.py中增加UA的設(shè)置缀磕,偽裝為瀏覽器的訪問
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'
5.2 class名稱中有空格
參考[5],空格用“.”替代空格
5.3 怎么解析本地文件
url使用file的地址符劣光,如下所示:
file:///path_of_directory/example.html