1. 程式人生 > >【Python資料分析】簡單爬蟲,爬取知乎神回覆

【Python資料分析】簡單爬蟲,爬取知乎神回覆

歡迎加入Python學習交流QQ群:535993938  禁止閒聊 ! 名額有限 ! 非喜勿進 !

      看知乎的時候發現了一個 “如何正確地吐槽” 收藏夾,裡面的一些神回覆實在很搞笑,但是一頁一頁地看又有點麻煩,而且每次都要開啟網頁,於是想如果全部爬下來到一個檔案裡面,是不是看起來很爽,並且隨時可以看到全部的,於是就開始動手了。

工具

1.Python 2.7

2.BeautifulSoup

分析網頁

我們先來看看知乎上該網頁的情況:

網址: ,容易看到,網址是有規律的,page慢慢遞增,這樣就能夠實現全部爬取了。

再來看一下我們要爬取的內容: 

我們要爬取兩個內容:問題和回答,回答僅限於顯示了全部內容的回答,如下面這種就不能爬取,因為好像無法展開(反正我不會。。),再說答案不全的話爬來也沒用,所以就不爬答案不全的了吧。

好,那麼下面我們要找到他們在網頁原始碼中的位置:

即我們找到問題的內容包含在<h2 class = "zm-item-title"><a tar...>中,那麼我們等會就可以在這個標籤裡面找問題。

然後是回覆:

有兩個地方都有回覆的內容,因為上面那個的內容還包括了<span..>等一些內容,不方便處理,我們爬下面那個的內容,因為那個裡面的內容純正無汙染。

修正前程式碼

好,這時候我們試著寫出python程式碼:

複製程式碼
# -*- coding: cp936 -*-
import urllib2
from BeautifulSoup import BeautifulSoup

f = open('howtoTucao.txt','w')     #開啟檔案

for pagenum in range(1,21):        #從第1頁爬到第20頁

    strpagenum = str(pagenum)      #頁數的str表示
    print "Getting data for Page " + strpagenum   #shell裡面顯示的,表示已爬到多少頁
url = "http://www.zhihu.com/collection/27109279?page="+strpagenum #網址 page = urllib2.urlopen(url) #開啟網頁 soup = BeautifulSoup(page) #用BeautifulSoup解析網頁 #找到具有class屬性為下面兩個的所有Tag ALL = soup.findAll(attrs = {'class' : ['zm-item-title','zh-summary summary clearfix'] }) for each in ALL : #列舉所有的問題和回答 #print type(each.string) #print each.name if each.name == 'h2' : #如果Tag為h2型別,說明是問題 print each.a.string #問題中還有一個<a..>,所以要each.a.string取出內容 if each.a.string: #如果非空,才能寫入 f.write(each.a.string) else : #否則寫"No Answer" f.write("No Answer") else : #如果是回答,同樣寫入 print each.string if each.string: f.write(each.string) else : f.write("No Answer") f.close() #關閉檔案
複製程式碼

程式碼雖然不常,可是寫了我半天,開始各種出問題。

執行

然後我們執行就可以爬了:

修正前結果

等執行完畢,我們開啟檔案howtoTucao.txt,可以看到,這樣就爬取成功了。只是格式可能還是有點問題,原來是我No Answer沒加換行,所以No Answer還會混到文本里面去,加兩個換行就可以了。

結果在這 : 點我

說明

他跟我寫的不同,大家也可以看看,這裡並無借鑑與抄襲。    

優化及修正

文章發出後,收到了一些朋友,前輩的指導,進行了修正:

1.可以爬取全部內容

2.格式的修正

由上圖我們知道,全部內容是在content hidden中的,之前我因為不知道如何處理<span..那一段,所以就沒有爬全部內容,而是簡略地爬取了部分內容。

其實去掉那一段並不難,用正則表示式匹配:

1 nowstring = re.sub('<s.+>\n<a.+>\n<.+>\n','',each.a.string)

即可。

然後就是一些格式的整理,由下圖我們看到,爬取出的內容會有很多&lt;..&gt; 這隻有html才能夠解析,放到txt檔案中就不能解析,從而出現這些字元,影響閱讀,所以我們也用正則將它們去掉。

除了&lt;br&gt;用換行符代替外,其餘的我們都用''空串來代替,並且將圖片等也換掉。

修正後代碼

複製程式碼
# -*- coding: cp936 -*-
import urllib2
import re
from BeautifulSoup import BeautifulSoup

f = open('howtoTucao.txt','w')     #open the file

for pagenum in range(1,21):      

    strpagenum = str(pagenum)
    print "Getting data for Page " + strpagenum   #for we can see the process in shell
    url = "http://www.zhihu.com/collection/27109279?page="+strpagenum
    page = urllib2.urlopen(url)     #get the web page
    soup = BeautifulSoup(page)      #use BeautifulSoup to parsing the web page
    
    ALL = soup.findAll(attrs = {'class' : ['zm-item-title','content hidden'] })

    for each in ALL :
        if each.name == 'h2' :
            nowstring = re.sub('<s.+>\n<a.+>\n<.+>\n','',each.a.string)
            nowstring = re.sub('&lt;br&gt;','\n',nowstring)
            nowstring = re.sub('&lt;\w+&gt;','',nowstring)
            nowstring = re.sub('&lt;/\w+&gt;','',nowstring)
            nowstring = re.sub('&lt;.+&gt;','\n圖片\n',nowstring)
            nowstring = re.sub('&quot;','"',nowstring)
            print nowstring
            if nowstring:
                f.write(nowstring)
            else :
                f.write("\n No Answer \n")
        else :
            nowstring = re.sub('<s.+>\n<a.+>\n<.+>\n','',each.string)
            nowstring = re.sub('&lt;br&gt;','\n',nowstring)
            nowstring = re.sub('&lt;\w+&gt;','',nowstring)
            nowstring = re.sub('&lt;/\w+&gt;','',nowstring)
            nowstring = re.sub('&lt;.+&gt;','\n圖片\n',nowstring)
            nowstring = re.sub('&quot;','"',nowstring)
            print nowstring
            if nowstring:
                f.write(nowstring)
            else :
                f.write("\n No Answer \n")
f.close()                                 #close the file
複製程式碼

修正後結果

這樣就可以了。

歡迎加入Python學習交流QQ群:535993938  禁止閒聊 ! 名額有限 ! 非喜勿進 !