Python爬蟲實例(二)使用selenium抓取斗魚直播平台數據


程序說明:抓取斗魚直播平台的直播房間號及其觀眾人數,最后統計出某一時刻的總直播人數和總觀眾人數。

過程分析:

一、進入斗魚首頁http://www.douyu.com/directory/all

進入平台首頁,來到頁面底部點擊下一頁,發現url地址沒有發生變化,這樣的話再使用urllib2發送請求將獲取不到完整數據,這時我們可以使用selenium和PhantomJS來模擬瀏覽器點擊下一頁,這樣就可以獲取完整響應數據了。

首先檢查下一頁元素,如下:

<a href="#" class="shark-pager-next">下一頁</a>

使用selenium和PhantomJS模擬點擊,代碼如下:

from selenium import webdriver
# 使用PhantomJS瀏覽器創建瀏覽器對象
driver = webdriver.PhantomJS()
# 使用get方法加載頁面
driver.get("https://www.douyu.com/directory/all")
# class="shark-pager-next"是下一頁按鈕,click() 是模擬點擊
driver.find_element_by_class_name("shark-pager-next").click()
# 打印頁面頁面查看
print driver.page_source

這樣就可以通過設置一個循環條件,一直點擊下去,直到頁面加載完。循環終止的條件為最后一頁,進入最后一頁,檢查下一頁元素:

<a href="#" class="shark-pager-next shark-pager-disable shark-pager-disable-next">下一頁</a>

對比發現:當出現"shark-pager-disable-next",下一頁無法點擊,這就是循環停止的條件。

# 如果在頁面源碼里沒有找到"shark-pager-disable-next",其返回值為-1,可依次作為判斷條件
driver.page_source.find("shark-pager-disable-next")

二,對要提取的內容進行分析

查看直播房間名稱的元素,得到如下結果:

<span class="dy-name ellipsis fl">AI冬Ming</span>

使用BeatuifulSoup獲取元素,代碼如下:

# 房間名
names = soup.find_all("span", {"class" : "dy-name ellipsis fl"})

查看觀看人數的元素,得到如下結果:

<span class="dy-num fr">75.6萬</span>

使用BeatuifulSoup獲取元素,代碼如下:

# 觀眾人數
numbers = soup.find_all("span", {"class" :"dy-num fr"})

具體過程大概如此,下面是完整代碼:

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

from selenium import webdriver
from bs4 import BeautifulSoup as bs
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

class Douyu():
    
    def __init__(self):
        self.driver = webdriver.PhantomJS()
        self.num = 0
        self.count = 0

    def douyuSpider(self):
        self.driver.get("https://www.douyu.com/directory/all")
        while True:
            soup = bs(self.driver.page_source, "lxml")
            # 房間名, 返回列表
            names = soup.find_all("span", {"class" : "dy-name ellipsis fl"})
            # 觀眾人數, 返回列表
            numbers = soup.find_all("span", {"class" :"dy-num fr"})

            for name, number in zip(names, numbers):
                print u"觀眾人數: -" + number.get_text().strip() + u"-\t房間名: " + name.get_text().strip()
                self.num += 1
                count = number.get_text().strip()
                if count[-1]=="":
                    countNum = float(count[:-1])*10000
                else:
                    countNum = float(count)
                self.count += countNum
            
            # 一直點擊下一頁
            self.driver.find_element_by_class_name("shark-pager-next").click()
            # 如果在頁面源碼里找到"下一頁"為隱藏的標簽,就退出循環
            if self.driver.page_source.find("shark-pager-disable-next") != -1:
                    break    

        print "當前網站直播人數:%s" % self.num
        print "當前網站觀眾人數:%s" % self.count
            

if __name__ == "__main__":
    d = Douyu()
    d.douyuSpider()

運行結果(部分展示):

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM