初始爬虫11

news/2024/10/4 21:12:56 标签: 爬虫, python, 开发语言

1.斗鱼selenium爬取

python"># -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

class Douyu(object):
    def __init__(self):
        self.url = 'https://www.douyu.com/directory/all'
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(10)  # 设置隐式等待,最大等待10秒

    def parse_data(self):
        room_list = self.driver.find_elements(By.XPATH, '//*[@id="listAll"]/section[2]/div[2]/ul/li/div')
        print(len(room_list))
        data_list = []

        # 遍历房间列表,从每一个房间节点获取数据
        for room in room_list:
            temp = {}
            # temp['title'] = room.find_element(By.XPATH, './div[2]/div[1]/a').text
            # temp['type'] = room.find_element(By.XPATH, './div[2]/div[2]/span/a').text
            # temp['owner'] = room.find_element(By.XPATH, './div[1]/div/a/div/div[2]/div/div[1]/div').text
            # temp['num'] = room.find_element(By.XPATH, './div[1]/div/a/div/div[2]/div/div[2]/span').text
            temp['picture'] = room.find_element(By.XPATH, './div[1]/picture/source[1]').get_attribute('srcset')
            # print(temp)
            data_list.append(temp)
        return data_list


    def run(self):
        self.driver.get(self.url)
        total_rooms = 0
        last_count = 0  # 上一次获取的房间数量
        while True:
            # 滚动到页面底部
            self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
            time.sleep(2)  # 等待页面加载新内容

            # 获取当前房间数据
            new_data = self.parse_data()
            total_rooms += len(new_data)
            print(f"Total rooms : {total_rooms}")

            # 检查当前房间数量
            if total_rooms == last_count:  # 如果新加载的房间数量没有增加,停止滚动
                print("No more new data to load.")
                break
            last_count = total_rooms  # 更新最后一次的房间数量

        print(f"Final total rooms fetched: {total_rooms}")
        self.driver.quit()  # 退出浏览器


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

2. request+mysql存储

python">import pymysql
import requests
from lxml import etree

# 第一步:请求百度首页并提取内容
url = 'https://www.baidu.com/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=headers)
html = etree.HTML(response.content.decode("utf-8"))

# 提取文本和链接
classes = ["normal", "c", "color", "t"]
extracted_data = []

for cls in classes:
    xpath_query = f'//div[contains(@class, "{cls}")]'
    elements = html.xpath(xpath_query)
    for element in elements:
        # 提取文本内容
        text = ''.join(element.xpath('.//text()')).strip()
        # 提取链接,假定链接是 a 标签的 href 属性
        link = element.xpath('.//a/@href')
        link = link[0] if link else "No link found"
        extracted_data.append((text, link))

# 第二步:连接 MySQL 数据库
connection = pymysql.connect(
    host='localhost',  # 数据库地址
    user='root',  # MySQL 用户名
    password='991016',  # MySQL 密码
    database='test',  # 数据库名称
    charset='utf8mb4',  # 确保字符集是 utf8mb4
    cursorclass=pymysql.cursors.DictCursor  # 使用字典形式的游标
)

try:
    with connection.cursor() as cursor:
        # 创建一个新表存储网页内容
        create_table_query = """
        CREATE TABLE IF NOT EXISTS web_content (
            id INT AUTO_INCREMENT PRIMARY KEY,
            text_content TEXT,
            link VARCHAR(255)
        );
        """
        cursor.execute(create_table_query)

        # 插入提取到的数据
        insert_query = "INSERT INTO web_content (text_content, link) VALUES (%s, %s)"
        cursor.executemany(insert_query, extracted_data)

        # 提交更改
        connection.commit()

        # 查询数据并验证是否成功存储
        cursor.execute("SELECT * FROM web_content")
        results = cursor.fetchall()
        for row in results:
            print(row)

finally:
    connection.close()

http://www.niftyadmin.cn/n/5690332.html

相关文章

vscode配置golang

1.安装golang解释器 从网址https://go.dev/dl/下载对应的golang解释器 2.配置环境 Extensions中搜索安装go 2.配置settings.json {"go.autocompleteUnimportedPackages": true,"go.gocodeAutoBuild": false,"explorer.confirmPasteNative"…

裸金属服务器与虚拟机、物理机区别

裸金属服务器:作为一种物理服务器架构,其显著特征在于其直接运行于物理硬件之上,摒弃了虚拟化层的介入。此设计旨在提供纯粹的计算能力,确保所有计算资源均直接服务于用户的应用,从而实现了计算效率与性能的显著提升。…

什么是虚拟化?| 裸机 vs 虚拟机 vs 容器

“云计算!DevOps!Docker!Kubernetes!……” 如果您是一名软件工程师,还没有遇到过以上这些流行词,那么您可能一直生活在与世隔绝的地方。 所有这些技术都与同一样东西有关,对,就是…

QT系统学习篇(5)-信号与槽

1、信号槽的优点 信号槽的优点,松散耦合,信号发送端和接收端本身没有关联,通过connect连接将两端耦合在一起。 myPushButton *btn3new myPushButton(this);btn3->setText("我的按钮");btn3->move(200,0);//发送者 信号 &…

<<迷雾>> 第6章 加法机的诞生(3)--三比特加法电路 示例电路

用全加器组成一个三比特加法电路 info::操作说明 鼠标单击开关切换开合状态 primary::在线交互操作链接 https://cc.xiaogd.net/?startCircuitLinkhttps://book.xiaogd.net/cyjsjdmw-examples/assets/circuit/cyjsjdmw-ch03-02-3-bit-adder.txt 原图 加法机的简单图示 info::操…

市场中的新兴力量与未来发展

在当前瞬息万变的全球金融市场中,期货交易以其高杠杆与灵活性,吸引了越来越多的投资者参与其中。大粤期货作为中国期货行业的新兴力量,凭借其创新的交易平台、广泛的产品线及专业的风险管理服务,迅速在市场中崭露头角。本文将介绍…

websockets库使用(基于Python)

主要参考资料: 【Python】websockets库的介绍及用法: https://blog.csdn.net/qq_53871375/article/details/135920231 python模块websockets,浏览器与服务器之间的双向通信: https://blog.csdn.net/randy521520/article/details/134752051 目录 websocke…

HTTP【网络】

文章目录 HTTPURL(Uniform Resource Lacator) HTTP协议格式HTTP的方法HTTP的状态码HTTP常见的Header HTTP 超文本传输协议,是一个简单的请求-响应协议,HTTP通常运行在TCP之上 URL(Uniform Resource Lacator) 一资源定位符,也就是通常所说的…