溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

發(fā)布時間:2021-10-28 16:54:30 來源:億速云 閱讀:150 作者:柒染 欄目:編程語言

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子,針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

背景:

PySpider:一個國人編寫的強大的網(wǎng)絡(luò)爬蟲系統(tǒng)并帶有強大的WebUI。采用Python語言編寫,分布式架構(gòu),支持多種數(shù)據(jù)庫后端,強大的WebUI支持腳本編輯器,任務(wù)監(jiān)視器,項目管理器以及結(jié)果查看器。

前提:

你已經(jīng)安裝好了Pyspider 和 MySQL-python(保存數(shù)據(jù))

如果你還沒安裝的話,請看看我的前一篇文章,防止你也走彎路。

  • Pyspider 框架學(xué)習(xí)時走過的一些坑

  • HTTP 599: SSL certificate problem: unable to get local issuer  certificate錯誤

我所遇到的一些錯誤:

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

首先,本爬蟲目標:使用 Pyspider 框架爬取 V2EX 網(wǎng)站的帖子中的問題和內(nèi)容,然后將爬取的數(shù)據(jù)保存在本地。

V2EX 中大部分的帖子查看是不需要登錄的,當(dāng)然也有些帖子是需要登陸后才能夠查看的。(因為后來爬取的時候發(fā)現(xiàn)一直 error  ,查看具體原因后才知道是需要登錄的才可以查看那些帖子的)所以我覺得沒必要用到 Cookie,當(dāng)然如果你非得要登錄,那也很簡單,簡單地方法就是添加你登錄后的  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” 按鈕

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

替換 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ù)對結(jié)果進行解析。

  • @every) 修飾器,表示 on_start 每天會執(zhí)行一次,這樣就能抓到***的帖子了。

  • validate_cert=False 一定要這樣,否則會報 HTTP 599: SSL certificate problem: unable to  get local issuer certificate錯誤

首頁:

點擊綠色的 run 執(zhí)行,你會看到 follows 上面有一個紅色的 1,切換到 follows 面板,點擊綠色的播放按鈕:

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

 Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

第二張截圖一開始是出現(xiàn)這個問題了,解決辦法看前面寫的文章,后來問題就不再會出現(xiàn)了。

Tab 列表頁 :

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

在 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 天內(nèi)頁面有效,不會再次進行更新抓取

Go列表頁 :

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

代碼:

@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):

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

你可以看到結(jié)果里面出現(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)自動翻頁功能

去掉后的運行截圖:

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

實現(xiàn)自動翻頁后的截圖:

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

此時我們已經(jīng)可以匹配了所有的帖子的 url 了。

點擊每個帖子后面的按鈕就可以查看帖子具體詳情了。

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

代碼:

@config(priority=2)     def detail_page(self, response):         title = response.doc('h2').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()

查看爬蟲運行結(jié)果:

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

先debug下,再調(diào)成running。pyspider框架在windows下的bug

設(shè)置跑的速度,建議不要跑的太快,否則很容易被發(fā)現(xiàn)是爬蟲的,人家就會把你的IP給封掉的

查看運行工作

查看爬取下來的內(nèi)容

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子

然后再本地數(shù)據(jù)庫GUI軟件上查詢下就可以看到數(shù)據(jù)已經(jīng)保存到本地了。

自己需要用的話就可以導(dǎo)入出來了。

在開頭我就告訴大家爬蟲的代碼了,如果詳細的看看那個project,你就會找到我上傳的爬取數(shù)據(jù)了。(僅供學(xué)習(xí)使用,切勿商用!)

當(dāng)然你還會看到其他的爬蟲代碼的了,如果你覺得不錯可以給個  Star,或者你也感興趣的話,你可以fork我的項目,和我一起學(xué)習(xí),這個項目長期更新下去。

代碼:

# 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('h2').text()         content = response.doc('div.topic_content').html().replace('"', '\\"')         self.add_question(title, content)  #插入數(shù)據(jù)庫         return {             "url": response.url,             "title": title,             "content": content,         }

關(guān)于Pyspider框架中Python如何爬取V2EX網(wǎng)站帖子問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI