多線程Beatiful Soup爬取鬥魚所有線上主播的資訊

來源:互聯網
上載者:User

標籤:mic   user   ext   地址   soup   ima   else   color   direct   

  最近看了個爬蟲的教程,想著自己也常在鬥魚看直播,不如就拿它來練練手。於是就寫了個爬取鬥魚所有線上主播的資訊,分別為類別、主播ID、房間標題、人氣值、房間地址。

  需要用到的工具python3下的bs4,requests,pymongo。我用的IDE是pycharm,感覺這個軟體實在太強大,有點離開它什麼都不會的感覺,資料庫Mongodb,結合pycharm工具可以直接在右側顯示資料。

#-*- coding:utf-8 -*-from bs4 import BeautifulSoupimport requests, time ,datetimeimport jsonimport pymongoclass douyu_host_info():    def __init__(self):        self.date_time = datetime.datetime.now().strftime(‘%Y-%m-%d_%H-%M‘)        self.host_url = ‘https://www.douyu.com‘        self.list_data = []        self.urls_list = []        self.headers = {        ‘User-Agent‘:‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36‘,        }    def get_url(self):        #擷取所有類別的網站地址        urls = ‘https://www.douyu.com/directory‘        data = requests.get(urls)        Soup = BeautifulSoup(data.text, ‘lxml‘)        list = Soup.select(‘.r-cont.column-cont  dl  dd  ul  li  a‘)        for i in list:            urls = i.get(‘href‘)            self.urls_list.append(urls)        print (self.urls_list)        return self.urls_list    def get_info(self, url):        #查詢所需資訊並寫調用寫入資料庫及本地磁碟的函數        time.sleep(1) #避免伺服器承壓過大,每個網站爬取設定1s間隔        url = self.host_url + url        print (‘Now start open {}‘.format(url))        get_data = requests.get(url, headers=self.headers)        Soup = BeautifulSoup(get_data.text, ‘lxml‘)        names = Soup.select(‘.ellipsis.fl‘)        nums = Soup.select(‘.dy-num.fr‘)        titles = Soup.select(‘.mes h3‘)        hrefs = Soup.select(‘#live-list-contentbox  li  a‘)        #網站中帶directory時只是一個分類頁面沒有主播資訊        if ‘directory‘ in url:            pass        #異常處理,有少數類別的HTML元素有差別,這裡就捨棄了        try:            category = Soup.select(‘.listcustomize-topcon-msg h1‘)[0].get_text()        except:            category = ‘秩名類別‘        for name, num, href, title in zip(names, nums, hrefs, titles):            data = {                ‘類別‘: category,                ‘主播‘: name.get_text(),                ‘標題‘: title.get_text().split(‘\n‘)[-1].strip(),                ‘連結‘: ‘https://www.douyu.com‘ + href.get(‘href‘),                #把人氣指數轉換成以萬為單位的浮點型,方便後面計算尋找                ‘人氣指數‘: float(num.get_text()[:-1]) if ‘萬‘in num.get_text() else float(num.get_text())/10000,            }            if data[‘人氣指數‘] > 2:                print (data)                self.w_to_local(data)                self.w_to_db(data)    def open_data(self, date_time):        #需要用到時可以輸入指定時間點讀取本地儲存的資料        with open(‘D:\douyu_host{}.csv‘.format(date_time), ‘r‘) as r_data:            r_data = json.load(r_data)            for i in r_data:                print (i)    def w_to_local(self,data):        #在將資料寫入資料庫的同時在本地磁碟儲存一份        with open(‘D:\douyu_host{}.csv‘.format(self.date_time), ‘a‘) as w_data:            json.dump(data, w_data)    def w_to_db(self, data):        #將資料寫入一個以時間為尾碼的資料庫表, data需要是字典格式        client = pymongo.MongoClient(‘localhost‘, 27017)        walden = client[‘walden_{}‘.format(self.date_time)]        sheet_tab = walden[‘sheet_tab‘]        if data is not None:            sheet_tab.insert_one(data)    def check_from_db(self, date_time):        #輸入時間從資料庫查詢相關人氣資訊        client = pymongo.MongoClient(‘localhost‘, 27017)        walden = client[‘walden_{}‘.format(date_time)]        sheet_tab = walden[‘sheet_tab‘]        for data in sheet_tab.find({‘人氣指數‘:{‘$gte‘:40}}):            print (data)

  本來沒想用類來寫的,後來發現很多資料傳來傳去很亂,而且重要的資料存放區時間不好統一,於是就寫在一個類裡了。裡面很關鍵的一點,用select模組選取元素路徑,如。

  複製出來的是很長的一段路徑,可以慢慢觀察選取主要的關鍵字段就好了。

  然後建立一個py檔案用來調用之前寫好的類,執行個體化後,用pool多線程運行,結果就出來了。

#-*- coding:utf-8 -*-import timefrom multiprocessing import Poolfrom test0822 import douyu_host_infodouyu = douyu_host_info()if __name__ == ‘__main__‘:    #多線程爬取資料    urls_list = douyu.get_url()    pool = Pool()    pool.map(douyu.get_info, urls_list)

來個運行後的全景。

 

多線程Beatiful Soup爬取鬥魚所有線上主播的資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.