Pyspider框架 —— Python爬蟲實戰(zhàn)之爬取 V2EX 網(wǎng)站帖子
背景:
PySpider:一個國人編寫的強大的網(wǎng)絡爬蟲系統(tǒng)并帶有強大的WebUI。采用Python語言編寫,分布式架構,支持多種數(shù)據(jù)庫后端,強大的WebUI支持腳本編輯器,任務監(jiān)視器,項目管理器以及結果查看器。在線示例: http://demo.pyspider.org/
官方文檔: http://docs.pyspider.org/en/l...
Github : https://github.com/binux/pysp...
本文爬蟲代碼 Github 地址:https://github.com/zhisheng17...
更多精彩文章可以在微信公眾號:猿blog 閱讀到,歡迎關注。
說了這么多,我們還是來看正文吧!
前提:
你已經(jīng)安裝好了Pyspider 和 MySQL-python(保存數(shù)據(jù))
如果你還沒安裝的話,請看看我的前一篇文章,防止你也走彎路。
我所遇到的一些錯誤:
首先,本爬蟲目標:使用 Pyspider 框架爬取 V2EX 網(wǎng)站的帖子中的問題和內容,然后將爬取的數(shù)據(jù)保存在本地。
V2EX 中大部分的帖子查看是不需要登錄的,當然也有些帖子是需要登陸后才能夠查看的。(因為后來爬取的時候發(fā)現(xiàn)一直 error ,查看具體原因后才知道是需要登錄的才可以查看那些帖子的)所以我覺得沒必要用到 Cookie,當然如果你非得要登錄,那也很簡單,簡單地方法就是添加你登錄后的 cookie 了。
我們在 https://www.v2ex.com/ 掃了一遍,發(fā)現(xiàn)并沒有一個列表能包含所有的帖子,只能退而求其次,通過抓取分類下的所有的標簽列表頁,來遍歷所有的帖子: https://www.v2ex.com/?tab=tech 然后是 https://www.v2ex.com/go/progr... ***每個帖子的詳情地址是 (舉例): https://www.v2ex.com/t/314683...
創(chuàng)建一個項目
在 pyspider 的 dashboard 的右下角,點擊 “Create” 按鈕
替換 on_start 函數(shù)的 self.crawl 的 URL:
- @every(minutes=24 * 60)
- def on_start(self):
- self.crawl('https://www.v2ex.com/', callback=self.index_page, validate_cert=False)
- self.crawl 告訴 pyspider 抓取指定頁面,然后使用 callback 函數(shù)對結果進行解析。
- @every) 修飾器,表示 on_start 每天會執(zhí)行一次,這樣就能抓到***的帖子了。
- validate_cert=False 一定要這樣,否則會報 HTTP 599: SSL certificate problem: unable to get local issuer certificate錯誤
首頁:
點擊綠色的 run 執(zhí)行,你會看到 follows 上面有一個紅色的 1,切換到 follows 面板,點擊綠色的播放按鈕:
第二張截圖一開始是出現(xiàn)這個問題了,解決辦法看前面寫的文章,后來問題就不再會出現(xiàn)了。
Tab 列表頁 :
在 tab 列表頁 中,我們需要提取出所有的主題列表頁 的 URL。你可能已經(jīng)發(fā)現(xiàn)了,sample handler 已經(jīng)提取了非常多大的 URL
代碼:
- @config(age=10 * 24 * 60 * 60)
- def index_page(self, response):
- for each in response.doc('a[href^="https://www.v2ex.com/?tab="]').items():
- self.crawl(each.attr.href, callback=self.tab_page, validate_cert=False)
- 由于帖子列表頁和 tab列表頁長的并不一樣,在這里新建了一個 callback 為 self.tab_page
- @config(age=10 24 60 * 60) 在這表示我們認為 10 天內頁面有效,不會再次進行更新抓取
Go列表頁 :
代碼:
- @config(age=10 * 24 * 60 * 60)
- def tab_page(self, response):
- for each in response.doc('a[href^="https://www.v2ex.com/go/"]').items():
- self.crawl(each.attr.href, callback=self.board_page, validate_cert=False)
帖子詳情頁(T):
你可以看到結果里面出現(xiàn)了一些reply的東西,對于這些我們是可以不需要的,我們可以去掉。
同時我們還需要讓他自己實現(xiàn)自動翻頁功能。
代碼:
- @config(age=10 * 24 * 60 * 60)
- def board_page(self, response):
- for each in response.doc('a[href^="https://www.v2ex.com/t/"]').items():
- url = each.attr.href
- if url.find('#reply')>0:
- url = url[0:url.find('#')]
- self.crawl(url, callback=self.detail_page, validate_cert=False)
- for each in response.doc('a.page_normal').items():
- self.crawl(each.attr.href, callback=self.board_page, validate_cert=False) #實現(xiàn)自動翻頁功能
去掉后的運行截圖:
實現(xiàn)自動翻頁后的截圖:
此時我們已經(jīng)可以匹配了所有的帖子的 url 了。
點擊每個帖子后面的按鈕就可以查看帖子具體詳情了。
代碼:
- @config(priority=2)
- def detail_page(self, response):
- title = response.doc('h1').text()
- content = response.doc('div.topic_content').html().replace('"', '\\"')
- self.add_question(title, content) #插入數(shù)據(jù)庫
- return {
- "url": response.url,
- "title": title,
- "content": content,
- }
插入數(shù)據(jù)庫的話,需要我們在之前定義一個add_question函數(shù)。
- #連接數(shù)據(jù)庫
- def __init__(self):
- self.db = MySQLdb.connect('localhost', 'root', 'root', 'wenda', charset='utf8')
- def add_question(self, title, content):
- try:
- cursor = self.db.cursor()
- sql = 'insert into question(title, content, user_id, created_date, comment_count) values ("%s","%s",%d, %s, 0)' % (title, content, random.randint(1, 10) , 'now()'); #插入數(shù)據(jù)庫的SQL語句
- print sql
- cursor.execute(sql)
- print cursor.lastrowid
- self.db.commit()
- except Exception, e:
- print e
- self.db.rollback()
查看爬蟲運行結果:
先debug下,再調成running。pyspider框架在windows下的bug
設置跑的速度,建議不要跑的太快,否則很容易被發(fā)現(xiàn)是爬蟲的,人家就會把你的IP給封掉的
查看運行工作
查看爬取下來的內容
然后再本地數(shù)據(jù)庫GUI軟件上查詢下就可以看到數(shù)據(jù)已經(jīng)保存到本地了。
自己需要用的話就可以導入出來了。
在開頭我就告訴大家爬蟲的代碼了,如果詳細的看看那個project,你就會找到我上傳的爬取數(shù)據(jù)了。(僅供學習使用,切勿商用!)
當然你還會看到其他的爬蟲代碼的了,如果你覺得不錯可以給個 Star,或者你也感興趣的話,你可以fork我的項目,和我一起學習,這個項目長期更新下去。
***:
代碼:
- # created by 10412
- # !/usr/bin/env python
- # -*- encoding: utf-8 -*-
- # Created on 2016-10-20 20:43:00
- # Project: V2EX
- from pyspider.libs.base_handler import *
- import re
- import random
- import MySQLdb
- class Handler(BaseHandler):
- crawl_config = {
- }
- def __init__(self):
- self.db = MySQLdb.connect('localhost', 'root', 'root', 'wenda', charset='utf8')
- def add_question(self, title, content):
- try:
- cursor = self.db.cursor()
- sql = 'insert into question(title, content, user_id, created_date, comment_count) values ("%s","%s",%d, %s, 0)' % (title, content, random.randint(1, 10) , 'now()');
- print sql
- cursor.execute(sql)
- print cursor.lastrowid
- self.db.commit()
- except Exception, e:
- print e
- self.db.rollback()
- @every(minutes=24 * 60)
- def on_start(self):
- self.crawl('https://www.v2ex.com/', callback=self.index_page, validate_cert=False)
- @config(age=10 * 24 * 60 * 60)
- def index_page(self, response):
- for each in response.doc('a[href^="https://www.v2ex.com/?tab="]').items():
- self.crawl(each.attr.href, callback=self.tab_page, validate_cert=False)
- @config(age=10 * 24 * 60 * 60)
- def tab_page(self, response):
- for each in response.doc('a[href^="https://www.v2ex.com/go/"]').items():
- self.crawl(each.attr.href, callback=self.board_page, validate_cert=False)
- @config(age=10 * 24 * 60 * 60)
- def board_page(self, response):
- for each in response.doc('a[href^="https://www.v2ex.com/t/"]').items():
- url = each.attr.href
- if url.find('#reply')>0:
- url = url[0:url.find('#')]
- self.crawl(url, callback=self.detail_page, validate_cert=False)
- for each in response.doc('a.page_normal').items():
- self.crawl(each.attr.href, callback=self.board_page, validate_cert=False)
- @config(priority=2)
- def detail_page(self, response):
- title = response.doc('h1').text()
- content = response.doc('div.topic_content').html().replace('"', '\\"')
- self.add_question(title, content) #插入數(shù)據(jù)庫
- return {
- "url": response.url,
- "title": title,
- "content": content,
- }