1. 程式人生 > >用python實現的一個簡單的爬蟲

用python實現的一個簡單的爬蟲

在MOOC上學完了python的入門課程後,實現課後的一個小作業。

 對應的python的基礎:

對之前學到的python的基礎知識有了一個很好的回顧。用到的基本知識有:包的匯入,類的定義,if語句,for語句,字典,列表,的操作,正則的應用,sort函式的應用,lambda表示式,map函式。

 小程式的效果:

可以爬取某直播平臺分割槽下主播的姓名及觀眾的人數,並對爬取得資料進行排序。

import re #匯入庫
from urllib import request #匯入庫中的方法
#定義一個類
class Spider():
    url = 'https://www.panda.tv/cate/lol?pdt=1.24.s1.3.6mavo55dcno'
    root_pattern = '<div class="video-info">([\s\S]*?)</div>' #其中的“?”表示的是非貪婪的匹配
    name_pattern = '</i>([\s\S]*?)</span>' #用正則表示式來提取有效的資訊
    number_pattern = '<span class="video-number">([\s\S]*?)</span>'
    def __fetch_content(self):
        r = request.urlopen(Spider.url) #開啟連結
        htmls = r.read() #讀取連結的內容
        htmls = str(htmls, encoding = 'utf-8') #將其轉化為字串
        return htmls

    #對資料進行分析
    def __analysis(self, htmls):
        root_html = re.findall(Spider.root_pattern,htmls) #用正則表示式提取字串中有效的部分,root_html的型別是list
        anchors = []
        #用for迴圈遍歷list
        for html in root_html:
            name = re.findall(Spider.name_pattern, html) #用正則匹配有效名字
            number = re.findall(Spider.number_pattern, html) #用正則匹配有效數字
            anchor = {'name':name, 'number':number} #將資訊封裝成dict
            anchors.append(anchor) #將字典放進新的list
        return anchors

   #排序函式
    def __sort(self, anchors):
        anchors = sorted(anchors, key= self.__sort_seed,reverse = True)
        return anchors

    #生成排序種子的函式
    def __sort_seed(self, anchor):
        r = re.findall('\d*', anchor['number']) #正則匹配數字
        number = float(r[0])
        if '萬' in anchor['number']: #對“萬”進行區別處理
            number *= 10000
        return number

    #顯示函式(排序結果)
    def __show(self, anchors):
        for anchor in anchors:
            print(anchor['name']+ '------'+anchor['number'])

    #精煉資訊函式
    def __refine(self, anchors):
        l = lambda anchor:{'name':anchor['name'][0].strip(),
                           'number':anchor['number'][0]}
        return map(l, anchors)

    #入口函式
    def go(self):
        htmls = self.__fetch_content()
        anchors = self.__analysis(htmls)
        #print(anchors[8])
        anchors = list(self.__refine(anchors))
        anchors = self.__sort(anchors)
        self.__show(anchors)


spider = Spider()
spider.go()

學習的過程中,寫寫部落格記錄一下自己的學習過程!

ps:大週末的導師早上比我來的早,現在還在做實驗。老師都這個年紀了,還這麼拼!實在讓我汗顏。

年輕人就是要幹到底!