python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

網絡爬蟲 Scrapy 技術 糊說理道 糊說理道 2017-09-28

使用 scrapy 抓取知乎API數據並存儲到 sqlite3 和 csv文件中

1. 項目準備 —— 繼續使用 上一篇文章 中的項目做修改

2. 項目結構,新增了test目錄以及questionData.py文件,後續用來查看數據是否已經寫入數據庫

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

項目結構

3. 修改配置文件setting.py

(1)調高日誌級別,去除無用的干擾日誌

LOG_LEVEL= 'WARNING'

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

設置日誌級別

(2)去除中間件註釋,計算爬蟲耗時

SPIDER_MIDDLEWARES = {

'zhihuSpider.middlewares.ZhihuspiderSpiderMiddleware': 543,

}

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

去除中間件註釋

(3)去除 ITEM_PIPELINES 註釋,並添加一條規則

ITEM_PIPELINES = {

'zhihuSpider.pipelines.ZhihuspiderWriteToCSVPipeline': 300, # ZhihuspiderWriteToCSVPipeline 與 pipelines 中 class 名稱相同

'zhihuSpider.pipelines.ZhihuspiderWriteToDBPipeline': 400 # ZhihuspiderWriteToDBPipeline 與 pipelines 中 class 名稱相同

}

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

去除 ITEM_PIPELINES 註釋

4. 修改 middlewares.py 文件,計算爬蟲時間

(1) 導入 time 模塊

import time

(2)在 from_crawler 方法中添加以下內容,監聽爬蟲開始與結束

crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)

crawler.signals.connect(s.spider_closed, signal=signals.spider_closed)

(3)增加並修改 spider_opened 和 spider_closed 方法

def spider_opened(self, spider):

self.startTime = time.time()

print(' 爬蟲開始 '.center(50, "*"))

print((' 開始時間:%.2f ' % self.startTime).center(50, "*"))

def spider_closed(self, spider):

self.endTime = time.time()

_t = self.endTime - self.startTime

print((' 結束時間:%.2f ' % self.endTime).center(50, "*"))

print((' 耗時:%.2f s ' % _t).center(50, "*"))

print(' 爬蟲結束 '.center(50, "*"))

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

middlewares.py 文件

5. 修改 pipelines.py 處理數據

(1)增加 ZhihuspiderWriteToCSVPipeline 類 ,數據寫入到csv文件(異常暫不處理)

class ZhihuspiderWriteToCSVPipeline(object):

def open_spider(self, spider):

self.csvFile = open(os.path.abspath('../test.csv'), "w+",newline='')

try:

self.write = csv.writer(self.csvFile)

self.write.writerow(('id', '問題'))

except Exception as e:

pass

def close_spider(self, spider):

self.csvFile.close()

def process_item(self, item, spider):

try:

self.write.writerow((item["qId"], item["qTitle"]))

except BaseException as e:

pass

return item

(2)增加 ZhihuspiderWriteToDBPipeline 類,數據寫入到 sqlite3

class ZhihuspiderWriteToDBPipeline(object):

def open_spider(self, spider):

try:

self.conn = sqlite3.connect(os.path.abspath('../test.db'))

self.cursor = self.conn.cursor()

self.cursor.execute('create table question (qId varchar(20) primary key, qTitle varchar(20))')

conn.commit()

except BaseException as e:

pass

def close_spider(self, spider):

try:

self.cursor.close()

self.conn.commit()

self.conn.close()

except BaseException as e:

pass

def process_item(self, item, spider):

try:

self.cursor.execute('insert into question (qId, qTitle) values (?, ?)', (item["qId"], item["qTitle"]))

except BaseException as e:

pass

return item

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

pipelines.py

6. 修改 items.py 文件

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

items.py

7. 修改主爬蟲文件 questionSpider.py

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

questionSpider.py

8. 修改數據測試文件 questionData.py

import sqlite3,os

conn = sqlite3.connect(os.path.abspath('../test.db'))

cursor = conn.cursor()

cursor.execute('select * from question')

values = cursor.fetchall()

cursor.close()

conn.close()

print(values)

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

questionData.py

9. 最後運行爬蟲就可以了

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

csv 文件

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

數據庫中的部分數據

PS: 知乎接口查找, 打開 https://www.zhihu.com/explore,向下滾動會發現如下請求

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

查看地址以及請求參數

python3網絡爬蟲 (5)-使用 scrapy 抓取知乎API數據並存儲

也可以在底部查看請求參數


喜歡就點個贊吧!

另付源碼地址:https://gitee.com/vuji/python3-webcrawler/tree/master/demo4/zhihuSpider

相關推薦

推薦中...