第一個基于 Scrapy 框架的爬蟲
今天我們在上一節(jié)的基礎(chǔ)上使用 Scrapy 框架來完成對互動出版網(wǎng)的計算機(jī)類書籍爬取。這里請跟著我們先熟悉一遍 Scrapy 框架的使用,至于細(xì)節(jié)后面會慢慢介紹到。
1. 新建 Scrapy 項目
Scrapy 框架和 Django 框架類似,先使用命令行來開啟一個項目的最小工程。這里會創(chuàng)建 python 的虛擬環(huán)境,如果不熟悉 pyenv 工具的同學(xué),可以參考這里的文章。
# 新建scray-test目錄,后續(xù)會保存scrapy項目的相關(guān)代碼
[root@server ~]# mkdir scrapy-test
[root@server ~]# cd scrapy-test/
# 安裝scrapy的虛擬環(huán)境
[root@server scrapy-test]# pyenv virtualenv 3.8.1 scrapy-test
[root@server scrapy-test]# pyenv activate scrapy-test
pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior.
# 使用 pip 命令安裝 Scrapy 框架
(scrapy-test) [root@server scrapy-test]# pip install scrapy
使用命令行創(chuàng)建一個新的 Scrapy 項目:
(scrapy-test) [root@server scrapy-test]# scrapy startproject china_pub
New Scrapy project 'china_pub', using template directory '/root/.pyenv/versions/3.8.1/envs/scrapy-test/lib/python3.8/site-packages/scrapy/templates/project', created in:
/root/scrapy-test/china_pub
You can start your first spider with:
cd china_pub
scrapy genspider example example.com
查看創(chuàng)建好的 Scrapy 項目的文件結(jié)構(gòu):
(scrapy-test) [root@server scrapy-test]# tree .
.
└── china_pub
├── china_pub
│ ├── __init__.py
│ ├── items.py
│ ├── middlewares.py
│ ├── pipelines.py
│ ├── __pycache__
│ ├── settings.py
│ └── spiders
│ ├── __init__.py
│ └── __pycache__
└── scrapy.cfg
我們可以看到 Scrapy 命令給我們創(chuàng)建的項目目錄和文件,這里我們來簡單分析下這些目錄和文件的含義,后面在介紹 Scrapy 框架的架構(gòu)圖后,會對這些目錄以及 Scrapy 的運行有著深刻的理解:
- items.py:items.py 文件中一般用于定義 Item 對象,它用來指定爬取的數(shù)據(jù)的結(jié)構(gòu);
- middlewares.py:中間件文件,主要是處理 request 和 response 的中間過程;
- pipelines.py:項目的管道文件,它會對 items.py 中里面定義的數(shù)據(jù)進(jìn)行進(jìn)一步的加工與處理。啟用該 pipline 時需要在 settings.py 中進(jìn)行配置;
- settings.py:項目的配置文件,比如設(shè)置處理 Item 對象的 piplines、請求頭的 ‘’User-Agent" 字段、代理、Cookie等;
- spider 目錄:主要是存放爬取的動作及解析網(wǎng)頁數(shù)據(jù)的代碼。
2. 第一個基于 Scrapy 框架的爬蟲
首先我們來看 Scrapy 項目的 spider 目錄部分,新建一個 Python 文件,命名為:china_pub_crawler.py
。這個文件中我們會用到 Scrapy 框架中非常重要的 Spider 類:
class ChinaPubCrawler(Spider):
name = "China-Pub-Crawler"
start_urls = ["http://www.china-pub.com/Browse/"]
def parse(self, response):
pass
# ...
我們實現(xiàn)一個 ChinaPubCrawler
類,它繼承了 Scrapy 框架的 Spider
類,在這里我們會用到 Spider
類的兩個屬性和一個方法:
- name: 爬蟲名稱,后續(xù)在運行 Scrapy 爬蟲時會根據(jù)名稱運行相應(yīng)的爬蟲;
- start_urls:開始要爬取的 URL 列表,這個地址可以動態(tài)調(diào)整;
parse()
:該方法是默認(rèn)的解析網(wǎng)頁的回調(diào)方法。當(dāng)然這里我們也可以自定義相應(yīng)的函數(shù)來實現(xiàn)網(wǎng)頁數(shù)據(jù)提取;
我們思考下前面完成互動出版網(wǎng)的步驟:第一步是請求 http://www.china-pub.com/Browse/
這個網(wǎng)頁數(shù)據(jù),從中找出計算機(jī)分類的鏈接 URL。這一步我們可以這樣實現(xiàn):
class ChinaPubCrawler(Spider):
name = "China-Pub-Crawler"
start_urls = ["http://www.china-pub.com/Browse/"]
def parse(self, response):
"""
解析得到計算機(jī)互聯(lián)網(wǎng)分類urls,然后重新構(gòu)造請求
"""
for url in response.xpath("http://div[@id='wrap']/ul[1]/li[@class='li']/a/@href").getall():
# 封裝請求,交給引擎去下載網(wǎng)頁;注意設(shè)置處理解析網(wǎng)頁的回調(diào)方法
yield Request(url, callback=self.book_list_parse)
def book_list_parse(self, response):
pass
我們將起點爬取的 URL 設(shè)置為 http://www.china-pub.com/Browse/
,然后使用默認(rèn)的 parse()
解析這個網(wǎng)頁的數(shù)據(jù),提取到計算機(jī)分類的各個 URL 地址,然后使用 Scrapy 框架的 Request 類封裝 URL 請求發(fā)送給 Scrapy 的 Engine 模塊去繼續(xù)下載網(wǎng)頁。在 Request 類中我們可以設(shè)置請求網(wǎng)頁的解析方法,這里我們會專門定義一個 book_list_parse()
類來解析圖書列表的網(wǎng)頁。
為了能提取相應(yīng)的圖書信息數(shù)據(jù),我們要定義對應(yīng)的圖書 Item 類,位于 items.py 文件中,代碼內(nèi)容如下:
# -*- coding: utf-8 -*-
import scrapy
class ChinaPubItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
book_url = scrapy.Field()
author = scrapy.Field()
isbn = scrapy.Field()
publisher = scrapy.Field()
publish_date = scrapy.Field()
vip_price = scrapy.Field()
price = scrapy.Field()
這里正是我們前面定義的圖書信息的 key 值,只不過這里用一種比較規(guī)范的方式進(jìn)行了定義。
現(xiàn)在還有一個問題要解決:如何實現(xiàn)分頁的圖書數(shù)據(jù)請求?我們在 book_list_parse()
方法中可以拿到當(dāng)前解析的 URL,前面我們分析過:請求的 URL 中包含請求頁信息。
我們只需要將當(dāng)前 URL 的頁號加1,然后在構(gòu)造 Request 請求交給 Scrapy 框架的引擎去執(zhí)行即可,那么這樣不會一直請求下去嗎?我們只需要檢查 response
的狀態(tài)碼,如果是 404,表示當(dāng)前頁號已經(jīng)無效了,此時我們就不用再構(gòu)造下一個的請求了,來看代碼的實現(xiàn):
import re
from scrapy import Request
from scrapy.spiders import Spider
from ..items import ChinaPubItem
class ChinaPubCrawler(Spider):
name = "China-Pub-Crawler"
start_urls = ["http://www.china-pub.com/Browse/"]
def parse(self, response):
"""
解析得到計算機(jī)互聯(lián)網(wǎng)分類urls,然后重新構(gòu)造請求
"""
for url in response.xpath("http://div[@id='wrap']/ul[1]/li[@class='li']/a/@href").getall():
yield Request(url, callback=self.book_list_parse)
def book_list_parse(self, response):
# 如果返回狀態(tài)碼為404,直接返回
if response.status == 404:
return
# 解析當(dāng)前網(wǎng)頁的圖書列表數(shù)據(jù)
book_list = response.xpath("http://div[@class='search_result']/table/tr/td[2]/ul")
for book in book_list:
item = ChinaPubItem()
item['title'] = book.xpath("li[@class='result_name']/a/text()").extract_first()
item['book_url'] = book.xpath("li[@class='result_name']/a/@href").extract_first()
book_info = book.xpath("./li[2]/text()").extract()[0]
item['author'] = book_info.split('|')[0].strip()
item['publisher'] = book_info.split('|')[1].strip()
item['isbn'] = book_info.split('|')[2].strip()
item['publish_date'] = book_info.split('|')[3].strip()
item['vip_price'] = book.xpath("li[@class='result_book']/ul/li[@class='book_dis']/text()").extract()[0]
item['price'] = book.xpath("li[@class='result_book']/ul/li[@class='book_price']/text()").extract()[0]
yield item
# 生成下一頁url,交給Scrapy引擎再次發(fā)送請求
url = response.url
regex = "(http://.*/)([0-9]+)_(.*).html"
pattern = re.compile(regex)
m = pattern.match(url)
if not m:
return []
prefix_path = m.group(1)
current_page = m.group(2)
suffix_path = m.group(3)
next_page = int(current_page) + 1
next_url = f"{prefix_path}{next_page}_{suffix_path}.html"
print("下一個url為:{}".format(next_url))
yield Request(next_url, callback=self.book_list_parse)
請求所有的 URL,解析相應(yīng)數(shù)據(jù),這些我們都有了,還差最后一步:數(shù)據(jù)入庫!這一步我們使用 item Pipeline 來實現(xiàn)將得到的 item 數(shù)據(jù)導(dǎo)入到 MongoDB 中。編寫的 item Pipeline 一般寫在 pipelines.py 中,來看看代碼樣子:
import pymongo
class ChinaPubPipeline:
def open_spider(self, spider):
"""連接mongodb,并認(rèn)證連接信息,內(nèi)網(wǎng)ip"""
self.client = pymongo.MongoClient(host='192.168.88.204', port=27017)
self.client.admin.authenticate("admin", "shencong1992")
db = self.client.scrapy_manual
# 新建一個集合保存抓取到的圖書數(shù)據(jù)
self.collection = db.china_pub_scrapy
def process_item(self, item, spider):
# 處理item數(shù)據(jù)
try:
book_info = {
'title': item['title'],
'book_url': item['book_url'],
'author': item['author'],
'isbn': item['isbn'],
'publisher': item['publisher'],
'publish_date': item['publish_date'],
'vip_price': item['vip_price'],
'price': item['price'],
}
self.collection.insert_one(book_info)
except Exception as e:
print("插入數(shù)據(jù)異常:{}".format(str(e)))
return item
def close_spider(self, spider):
# 關(guān)閉連接
self.client.close()
最后為了使這個 pipeline 生效,我們需要將這個 pipeline 寫到 settings.py 文件中:
# settings.py
# ...
ITEM_PIPELINES = {
'china_pub.pipelines.ChinaPubPipeline': 300,
}
# ...
最后,我們還需要在請求的頭部加上一個 User-Agent
參數(shù),這個設(shè)置在 settings.py
中完成:
# settings.py
# ...
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
# ...
整個爬蟲代碼就基本完成了,接下來開始我們激動人心的數(shù)據(jù)爬取吧!
3. 運行 Scrapy 項目,爬取數(shù)據(jù)
運行這個 scrapy 爬蟲的命令如下:
(scrapy-test) [root@server scrapy-test]# scrapy crawl China-Pub-Crawler
# 開始源源不斷的爬取數(shù)據(jù)
# ...
下面來看我們的視頻演示效果:
通過今天的一個簡單小項目,大家對 Scrapy 框架是否有了初步的印象?后面我們會仔細(xì)剖析 Scrapy 框架的各個模塊以及實現(xiàn)原理,讓大家真正理解和掌握 Scrapy 框架。
4. 小結(jié)
本節(jié)中我們基于 Scrapy 框架完成了和上一小節(jié)類似的功能:爬取互動出版網(wǎng)的計算機(jī)類書籍信息并保存到 MongoDB 中??梢钥吹胶苊黠@的區(qū)別是,Scrapy 中的代碼看起來比較規(guī)范和高大上,且我們不再去使用 requests 這樣的庫去請求網(wǎng)頁數(shù)據(jù),這些都在 Scrapy 內(nèi)部幫我們做好了。對于爬取一個大型網(wǎng)站時,Scrapy 還有更多的功能幫我們簡化代碼,比如登錄、Cookie 管理、代理請求等等。好了,第一部分的內(nèi)容就介紹到這里了,接下來我們就開始 Scrapy 框架的剖析之旅了!