利用selenium實現自動翻頁爬取某魚數據


基本思路:

首先用開發者工具找到需要提取數據的標簽列表:


利用xpath定位需要提取數據的列表


然后再逐個提取相應的數據:


保存數據到csv:


利用開發者工具找到下一頁按鈕所在標簽:


利用xpath提取此標簽對象並返回:


調用點擊事件,並循環上述過程:


最終效果圖:


代碼:

from selenium import webdriver
import time
import re

class Douyu(object):

    def __init__(self):
        # 開始時的url
        self.start_url = "https://www.douyu.com/directory/all"
        # 實例化一個Chrome對象
        self.driver = webdriver.Chrome()
        # 用來寫csv文件的標題
        self.start_csv = True

    def __del__(self):
        self.driver.quit()

    def get_content(self):
        # 先讓程序兩秒,保證頁面所有內容都可以加載出來
        time.sleep(2)
        item = {}
        # 獲取進入下一頁的標簽
        next_page = self.driver.find_element_by_xpath("//span[text()='下一頁']/..")
        # 獲取用於判斷是否是最后一頁的屬性
        is_next_url = next_page.get_attribute("aria-disabled")
        # 獲取存儲信息的所有li標簽的列表
        li_list = self.driver.find_elements_by_xpath("//ul[@class='layout-Cover-list']//li")
        
        # 提取需要的數據
        for li in li_list:
            
            item["user-id"] = li.find_element_by_xpath(".//div[@class='DyListCover-userName']").text
            item["img"] = li.find_element_by_xpath(".//div[@class='DyListCover-imgWrap']//img").get_attribute("src")
            item['class-name'] = li.find_element_by_xpath(".//span[@class='DyListCover-zone']").text
            item["click-hot"] = li.find_element_by_xpath(".//span[@class='DyListCover-hot']").text
            item["click-hot"] = re.sub(r'\n','',item['click-hot'])
            
            # 保存數據
            self.save_csv(item)
        
        # 返回是否有下一頁和下一頁的點擊事件的標簽,
        return next_page,is_next_url

    def save_csv(self,item):
        # 將提取存放到csv文件中的內容連接為csv格式文件
        str = ','.join([i for i in item.values()])

        with open('./douyu.csv','a',encoding='utf-8') as f:
            if self.start_csv:
                f.write("用戶id,image,所屬類,點擊熱度\n")
                self.start_csv = False
            # 將字符串寫入csv文件
            f.write(str)
            f.write('\n')
        print("save success")

    def run(self):
        # 啟動chrome並定位到相應頁面
        self.driver.get(self.start_url)

        while True:
            # 開始提取數據,並獲取下一頁的元素
            next_page,is_next = self.get_content()
            if is_next!='false':
                break
            # 點擊下一頁
            next_page.click()

if __name__=='__main__':
    douyu_spider = Douyu()
    douyu_spider.run()

歡迎關注公眾號:Python爬蟲數據分析挖掘,回復【開源源碼】免費獲取更多開源項目源碼

公眾號每日更新python知識和【免費】工具


免責聲明!

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



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