Python爬蟲實戰--鬥魚直播爬蟲

前言:
稍微總結一下前面我們所學到的內容吧!在前面的實戰學習中,我們學會如何使用requests來獲取網頁源碼,並從中提取出我們所需要的數據, 那接下來,我們也將進一步學會使用selenium獲取網頁,分析網頁,和提取數據。
目標站點分析
目標URL:https://www.douyu.com/directory/all
明確內容:
在這裏插入圖片描述
本次爬蟲實戰裏,我們將要爬取鬥魚網站上面所有的房間信息,並提取我們的目標數據:房間名,房間鏈接,房主,房間分類,觀看人數等紅色方框中的數據。
翻頁策略:
之前講過,我們在翻頁是,有三種操作模式:
1.直接查找頁面之間的聯繫,如:/pnXX/,這只需要XX遞增,便可以遍歷所有的頁面了
2.對於AJAX加載的頁面,我們需要找到接口,並請求它,獲取頁面信息,如新浪微博
3.通過找到,下一頁的按鈕,再使用selenium,點擊按鈕,完成翻頁
這裏我們可以採用第三種,來獲取下一頁的頁面信息
在這裏插入圖片描述

 # 3.點擊下一頁
        print('Next Page!')
        temp_list = self.driver.find_elements_by_class_name("shark-pager-next")
        # 4.進行循環獲取所有的房間信息
        while len(temp_list) > 0 and times < 3:
            times += 1
            temp_list[0].click()
            time.sleep(3)
            item_list = self.get_room_info()
            self.save_item_list(item_list)
            print('Next Page!')
            temp_list = self.driver.find_elements_by_class_name("shark-pager-next")

提取數據

    def get_room_info(self):
        li_list = self.driver.find_elements_by_xpath("//ul[@id='live-list-contentbox']/li")
        item_list = []
        for li in li_list:
            room_name = li.find_element_by_xpath("./a").get_attribute("title")
            room_link = li.find_element_by_xpath("./a").get_attribute("href")
            room_img = li.find_element_by_xpath("./a/span/img").get_attribute("src")
            room_category = li.find_element_by_xpath(".//span[@class='tag ellipsis']").text
            room_author = li.find_element_by_xpath(".//span[@class='dy-name ellipsis fl']").text
            watch_number = li.find_element_by_xpath(".//span[@class='dy-num fr']").text
            item = dict(
                room_name=room_name,
                room_link=room_link,
                room_img=room_img,
                room_category=room_category,
                room_author=room_author,
                watch_number=watch_number,
            )
            item_list.append(item)
            # print(item)
        return item_list

戰果展示
在這裏插入圖片描述
還是留個小作業吧~請大家進一步完善代碼,並將提取的數據存入到數據庫中。
源碼地址:https://github.com/NO1117/Douyu_Spider
Python交流羣:942913325 歡迎大家一起交流學習

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