利用Python寫百度貼吧爬蟲

  最近,我們這邊需要做一次防爬蟲和機器蜘蛛的困擾,感覺困惑,有點無從入手,倒不如,直接用Python來寫一個Spiner理解其各種原理,再下手也不遲啊,於是便立刻去寫一個爬蟲程序。

使用方法:

新建一個BugBaidu.py文件,然後將代碼複製到裏面後,雙擊運行。

程序功能:

將貼吧中樓主發佈的內容打包txt存儲到本地。

好,不廢話,直接上代碼:

#!/usr/bin/python
#-*- coding: utf-8 -*-

import string
import urllib2
import re


# ----------- 處理頁面上的各種標籤 -----------
class HTML_Tool:
    # 用非 貪婪模式 匹配 \t 或者 \n 或者 空格 或者 超鏈接 或者 圖片
    BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)")

    # 用非 貪婪模式 匹配 任意<>標籤
    EndCharToNoneRex = re.compile("<.*?>")

    # 用非 貪婪模式 匹配 任意<p>標籤
    BgnPartRex = re.compile("<p.*?>")
    CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)")
    CharToNextTabRex = re.compile("<td>")

    # 將一些html的符號實體轉變爲原始符號
    replaceTab = [("<", "<"), (">", ">"), ("&", "&"), ("&", "\""), (" ", " ")]

    def Replace_Char(self, x):
        x = self.BgnCharToNoneRex.sub("", x)
        x = self.BgnPartRex.sub("\n    ", x)
        x = self.CharToNewLineRex.sub("\n", x)
        x = self.CharToNextTabRex.sub("\t", x)
        x = self.EndCharToNoneRex.sub("", x)

        for t in self.replaceTab:
            x = x.replace(t[0], t[1])
        return x


class Yzw_Spider:
    # 申明相關的屬性
    def __init__(self, url):
        self.myUrl = url + '?see_lz=1'
        self.datas = []
        self.myTool = HTML_Tool()
        print u'已經啓動爬蟲,咔嚓咔嚓'

        # 初始化加載頁面並將其轉碼儲存

    def yzw_tieba(self):
        # 讀取頁面的原始信息並將其從utf-8轉碼
        myPage = urllib2.urlopen(self.myUrl).read().decode("utf-8")
        # 計算樓主發佈內容一共有多少頁
        endPage = self.page_counter(myPage)
        # 獲取該帖的標題
        title = self.find_title(myPage)
        print u'文章名稱:' + title
        # 獲取最終的數據
        self.save_data(self.myUrl, title, endPage)

        # 用來計算一共有多少頁

    def page_counter(self, myPage):
        # 匹配 "共有<span class="red">12</span>頁" 來獲取一共有多少頁
        myMatch = re.search(r'class="red">(\d+?)</span>', myPage, re.S)
        if myMatch:
            endPage = int(myMatch.group(1))
            print u'爬蟲報告:發現樓主共有%d頁的原創內容' % endPage
        else:
            endPage = 0
            print u'爬蟲報告:無法計算樓主發佈內容有多少頁!'
        return endPage

        # 用來尋找該帖的標題

    def find_title(self, myPage):
        # 匹配 <h1 class="core_title_txt" title="">xxxxxxxxxx</h1> 找出標題
        myMatch = re.search(r'<h1.*?>(.*?)</h1>', myPage, re.S)
        title = u'暫無標題'
        if myMatch:
            title = myMatch.group(1)
        else:
            print u'爬蟲報告:無法加載文章標題!'
            # 文件名不能包含以下字符: \ / : * ? " < > |
        title = title.replace('\\', '').replace('/', '').replace(':', '').replace('*', '').replace('?', '').replace('"',
                                                                                                                    '').replace(
            '>', '').replace('<', '').replace('|', '')
        return title


        # 用來存儲樓主發佈的內容

    def save_data(self, url, title, endPage):
        # 加載頁面數據到數組中
        self.get_data(url, endPage)
        # 打開本地文件
        f = open(title + '.txt', 'w+')
        f.writelines(self.datas)
        f.close()
        print u'爬蟲報告:文件已下載到本地並打包成txt文件'
        print u'請按任意鍵退出...'
        raw_input();

        # 獲取頁面源碼並將其存儲到數組中

    def get_data(self, url, endPage):
        url = url + '&pn='
        for i in range(1, endPage + 1):
            print u'爬蟲報告:爬蟲%d號正在加載中...' % i
            myPage = urllib2.urlopen(url + str(i)).read()
            # 將myPage中的html代碼處理並存儲到datas裏面
            self.deal_data(myPage.decode('utf-8'))


            # 將內容從頁面代碼中摳出來

    def deal_data(self, myPage):
        myItems = re.findall('id="post_content.*?>(.*?)</div>', myPage, re.S)
        for item in myItems:
            data = self.myTool.Replace_Char(item.replace("\n", "").encode('gbk'))
            self.datas.append(data + '\n')



            # -------- 程序入口處 ------------------


print u"""#---------------------------------------
#   程序:一站網爬蟲
#   語言:Python 2.7
#   操作:輸入網址後自動只看樓主並保存到本地文件
#   功能:將樓主發佈的內容打包txt存儲到本地。
#---------------------------------------
"""

# 以某熱點推薦爲例子
# bdurl = 'http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1'

print u'請輸入熱點的地址最後的數字串:'
bdurl = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/'))

# 調用
mySpider = Yzw_Spider(bdurl)
mySpider.yzw_tieba()

最後,得出的是一個.txt的文檔,但裏面有我需要爬下來的內容,如圖:

wKioL1dswuKi2EejAACbdXFGn5c989.png-wh_50


就這樣一個爬蟲程序就OK了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章