【Python爬虫】案例_斗鱼

声明:案例只用于学习,不得恶意使用

要求:获取直播间标题、类型、主播、热度,并实现翻页

定位随着网站更新可能不会实现,请自行更改

python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time

chrome_options = Options()
chrome_options.page_load_strategy = 'eager'
service = Service('chromedriver.exe路径')

class Douyu(object):

    def __init__(self):
        self.url = 'https://www.douyu.com/directory/all'
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        self.driver.implicitly_wait(5)

    def parse_data(self):
        time.sleep(3)
        data_list= []
        # 遍历房间列表,从每一个房间节点中获取数据
        for i in range(1,121):
            temp = {}
            temp['title'] = self.driver.find_element(By.XPATH, f'//li[{i}]/div/a/div[2]/div[1]/h3').text
            temp['type'] = self.driver.find_element(By.XPATH, f'//li[{i}]/div/a/div[2]/div[1]/span').text
            temp['owner'] = self.driver.find_element(By.XPATH, f'//li[{i}]/div/a/div[2]/div[2]/h2').text
            temp['num'] = self.driver.find_element(By.XPATH, f'//li[{i}]/div/a/div[2]/div[2]/span').text
            data_list.append(temp)
        return data_list

    def save_data(self,data_list):
        for data in data_list:
            print(data)

    def run(self):
        self.driver.get(self.url)
        while True:
            data_list = self.parse_data()
            self.save_data(data_list)

            try:
                el_next = self.driver.find_element(By.XPATH, '//*[@title="下一页"][@aria-disabled="false"]')
                self.driver.execute_script('scrollTo(0,1000000)')
                el_next.click()
            except:
                break

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

【Python爬虫】Selenium使用

相关推荐
ydd1001005 分钟前
寻找两个正序数组的中位数 Java 题解,二分分割详解
java·开发语言
65岁退休Coder14 分钟前
LangChain v1.3.4 笔记 - 07 补充:链式调用 LCEL
后端·python·langchain
卷无止境25 分钟前
FastAPI 部署在 Nginx 后面到底该怎么配
后端·python
半亩码田35 分钟前
C#转Python第3.1篇:Python 的 class 没有访问修饰符?面向对象的另一条路
开发语言·python·c#
Wzx1980121 小时前
python沙箱和docker沙箱你选对了吗?
开发语言·python·docker
Python私教1 小时前
签名 URL 刷新导致审批失效?别急着删掉所有 query
python·安全
牧羊人.3331 小时前
Python 办公自动化从入门到入土|09 数据容器之字典
开发语言·python
小僧景贤2 小时前
嵌入式C语言 第二篇:基础语法|嵌入式C与标准C的核心差异
c语言·开发语言·嵌入式c语言
Zane19942 小时前
类变量与实例变量:一个共享列表引发的线上事故
后端·python
阿pin2 小时前
Android随笔-AIDL
android·开发语言·aidl