使用 Selenium 实现自动化分页处理与信息提取

目录

  1. 项目背景与目标
  2. Selenium 环境配置
  3. 分页处理的基本思路
  4. 简化后的代码示例
  5. 总结

正文

1. 项目背景与目标

在进行 Web 自动化测试或数据抓取时,处理分页是一个常见的需求。通过 Selenium,我们可以自动化浏览多个分页并提取每页上的信息。本文将介绍如何使用 Selenium 实现这一目标,并提供简化和优化后的代码示例。

2. Selenium 环境配置

在开始之前,确保您已经安装了 Selenium 库和相应的 WebDriver(如 ChromeDriver)。以下是基本的环境配置代码:

python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import config

def setup_driver():
    # 加载配置
    selenium_config = {'chrome_driver_path':'chrome_driver_path','user_data_dir':'user_data_dir'}
    
    # 设置 ChromeDriver 的服务
    service = Service(selenium_config.chrome_driver_path)
    
    # 配置 ChromeDriver 的选项
    options = Options()
    options.add_argument(f'--user-data-dir={selenium_config['user_data_dir']}')
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
    
    # 初始化 WebDriver
    return webdriver.Chrome(service=service, options=options)
3. 分页处理的基本思路

我们需要遍历每一页上的文件链接,点击并提取信息。对于每一个文件链接,我们将在新标签页中打开它,获取所需的信息后再关闭标签页。最后,我们会处理下一页的按钮,直到没有下一页为止。

4. 代码示例

以下是简化和优化后的代码示例:

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

def setup_driver():
    import config
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    
    selenium_config = {'chrome_driver_path':'chrome_driver_path','user_data_dir':'user_data_dir'}
    service = Service(selenium_config.chrome_driver_path)
    options = Options()
    options.add_argument(f'--user-data-dir={selenium_config['user_data_dir']}')
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_argument("--user-agent=Mozilla/5.0")
    
    return webdriver.Chrome(service=service, options=options)

def click_all_links_on_page(driver):
# 执行操作
    pass

def paginate_and_scrape():
    driver = setup_driver()
    try:
        driver.get('https://XXXX/xXXX')
        # 等待页面加载完成
        WebDriverWait(driver, 60).until(lambda d: d.execute_script('return document.readyState') == 'complete')
        print(f'This page title is : {driver.title}')

        while True:
            click_all_links_on_page(driver)
            try:
            	# 获取下一页按钮元素
                next_button = driver.find_element(By.XPATH, "//button[@class='btn-next' and not(@disabled)]")
                next_button.click()
                # 等待页面加载完成
                WebDriverWait(driver, 20).until(lambda d: d.execute_script('return document.readyState') == 'complete')
            except Exception as e:
                print(f'Error occurred or no more next button: {e}')
                break
    finally:
        driver.quit()

if __name__ == "__main__":
    paginate_and_scrape()
5. 总结

本文介绍了如何使用 Selenium 实现自动化分页处理与信息提取。通过合理的代码简化和优化,可以提高脚本的可读性和执行效率。希望这篇博文能帮助您在实际项目中实现高效的网页信息提取。如果您有任何问题或建议,欢迎在评论区留言讨论。

相关推荐
Agent手记6 分钟前
成本数据多系统自动采集与分析实操指南:基于2026大模型Agent的超自动化实践
运维·人工智能·microsoft·ai·自动化
拉卡拉开放平台13 分钟前
支付系统在文旅场景的进阶之路:聚合收单、分账与自动化对账
大数据·人工智能·自动化
tedcloud1231 小时前
hello-agents部署教程:从零学习AI Agent开发
服务器·人工智能·学习·自动化·powerpoint
Agent产品评测局2 小时前
新能源制造供应链AI方案主流产品对比测评 —— 2026年企业级自动化选型深度指南
人工智能·ai·chatgpt·自动化·制造
码点滴2 小时前
Workload 自动化进化论:从手动运维到 AI 驱动的 Kubernetes 智能管控
运维·人工智能·kubernetes·自动化·workload
孙高飞3 小时前
直播预告 - 周日晚 7 点半-AI 驱动 UI 自动化
运维·自动化
小贺儿开发3 小时前
一句话生成网页 + 自动化办公(OpenCode + DeepSeek-V4)
css·自动化·html·工具·代码·网页·deepseek
qq_196976173 小时前
硬核多语言办公方案:基于Gemini境像站的实时翻译与双语文档自动化生成管道(国内免费镜像实测)
运维·自动化
Agent手记3 小时前
环保排放数据自动上报全流程自动化—— 2026企业级智能体(Agent)落地全指南
运维·人工智能·ai·自动化
yzx9910134 小时前
人工智能写作开发:从自动化内容到真正的创造力
人工智能·自动化·ai写作