用selenium爬取动态网页

Selenium 是一个用于自动化 Web 浏览器的工具,适用于爬取动态网页。下面是一个使用 Python 和 Selenium 爬取动态网页的示例。假设我们要爬取一个加载动态内容的网页,并提取其中的一些数据。

环境准备

首先,确保你已经安装了以下工具:

Python:确保安装了 Python 3.x。

Selenium:使用以下命令安装 Selenium。

java 复制代码
pip install selenium

浏览器驱动:Selenium 需要浏览器驱动来与浏览器进行交互。以 Chrome 为例,你需要下载 ChromeDriver 并将其添加到系统路径中。

示例代码

下面是一个使用 Selenium 爬取动态网页的示例代码:

java 复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 配置 WebDriver(这里以 Chrome 为例)
options = webdriver.ChromeOptions()
options.add_argument("--headless")  # 无头模式
driver = webdriver.Chrome(executable_path='/path/to/chromedriver', options=options)

# 目标网页
url = 'https://example.com/dynamic-content'

try:
    # 打开目标网页
    driver.get(url)
    
    # 等待网页中的动态内容加载完毕(以某个元素的出现为标志)
    element_present = EC.presence_of_element_located((By.ID, 'element-id'))
    WebDriverWait(driver, 10).until(element_present)

    # 查找并提取所需的数据(这里以提取某个元素的文本为例)
    element = driver.find_element(By.ID, 'element-id')
    data = element.text
    print(f'Extracted data: {data}')

    # 如果需要处理更多动态加载的内容,可以重复上述操作
    # 例如,点击某个按钮加载更多内容:
    # load_more_button = driver.find_element(By.ID, 'load-more-button')
    # load_more_button.click()
    # WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'new-element-id')))
    # new_element = driver.find_element(By.ID, 'new-element-id')
    # new_data = new_element.text
    # print(f'Extracted new data: {new_data}')

finally:
    # 关闭 WebDriver
    driver.quit()
相关推荐
明月_清风2 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽11 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805116 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon17 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly17 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程17 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly19 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法