动态内容加载的解决方案:Selenium与Playwright对比故障排查实录

方案进程

plain 复制代码
2024-09-01 09:00 | 接到亚航航班数据采集需求
2024-09-01 11:30 | 首次尝试使用Selenium遭遇Cloudflare验证
2024-09-01 14:00 | 切换Playwright方案仍触发反爬机制
2024-09-01 16:30 | 引入爬虫代理IP+UA轮换策略
2024-09-02 10:00 | 双方案完整实现并通过压力测试

故障场景分析

1. 动态内容加载失败(Selenium案例)

python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException

# 亿牛云代理配置(实际使用需替换为有效凭证)www.16yun.com
PROXY_HOST = "PROXY.16yun.com"
PROXY_PORT = "31000"
PROXY_USER = "16YUN"
PROXY_PASS = "16IP"

def failed_selenium_case():
    chrome_options = Options()
    chrome_options.add_argument(f"--proxy-server=http://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}")
    chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...")
    
    driver = webdriver.Chrome(options=chrome_options)
    try:
        driver.get("https://www.airasia.cn/zh/cn")
        # 尝试获取动态加载的航班信息
        WebDriverWait(driver, 10).until(
            lambda d: d.find_element("css selector", ".flight-list")
        )
        print(driver.page_source)
    except TimeoutException:
        print("ERROR: 动态内容加载超时,触发反爬验证")
    finally:
        driver.quit()

2. 反爬机制突破分析

通过Wireshark抓包发现:

  • 单IP高频访问触发Cloudflare验证
  • 固定User-Agent被识别为自动化脚本
  • Cookie缺失导致会话状态异常

架构改进方案

双引擎解决方案对比实现

python 复制代码
# 公共配置参数
COMMON_CONFIG = {
    # 亿牛云代理配置(实际使用需替换为有效凭证)www.16yun.com
    "proxy": f"http://{16YUN}:{16IP}@{PROXY.16yun.com}:{31000}",
    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...",
    "cookies": [
        {'name': 'session_id', 'value': 'xxxxxx'},
        {'name': 'preferred_currency', 'value': 'CNY'}
    ]
}

# ----------------- Selenium 方案 -----------------
def improved_selenium():
    from selenium.webdriver import Chrome
    from selenium.webdriver import ChromeOptions
    
    options = ChromeOptions()
    options.add_argument(f"--proxy-server={COMMON_CONFIG['proxy']}")
    options.add_argument(f"user-agent={COMMON_CONFIG['user_agent']}")
    
    driver = Chrome(options=options)
    # 设置Cookies
    driver.get("https://www.airasia.cn/zh/cn")
    for cookie in COMMON_CONFIG['cookies']:
        driver.add_cookie(cookie)
    
    # 执行动态内容获取
    driver.refresh()
    # ...(数据采集逻辑)

# ----------------- Playwright 方案 -----------------
async def improved_playwright():
    from playwright.async_api import async_playwright
    
    async with async_playwright() as p:
        browser = await p.chromium.launch(
            proxy={"server": COMMON_CONFIG['proxy']},
            headless=False
        )
        context = await browser.new_context(
            user_agent=COMMON_CONFIG['user_agent']
        )
        
        # 设置Cookies
        await context.add_cookies(COMMON_CONFIG['cookies'])
        
        page = await context.new_page()
        await page.goto("https://www.airasia.cn/zh/cn")
        
        # Playwright的自动等待机制
        await page.wait_for_selector(".flight-list", timeout=15000)
        content = await page.content()
        print(content)
        
        await browser.close()

技术方案对比

特性 Selenium Playwright
执行速度 较慢(HTTP层通信) 快速(WebSocket协议)
浏览器支持 需独立安装驱动 内置Chromium/Firefox
自动等待机制 需手动实现 智能自动等待
代理配置 通过启动参数设置 支持多协议代理
无头模式性能 200-500ms/请求 50-150ms/请求

架构优化建议

  1. IP轮换策略:使用亿牛云代理服务实现每5次请求更换出口IP
  2. 混合验证突破
    • 首请求使用Selenium模拟真人操作
    • 后续数据采集使用Playwright提升效率
  3. 动态Cookie管理
python 复制代码
def update_cookies_dynamically(driver):
    new_cookies = get_cookies_from_api()  # 从认证接口获取新Cookies
    driver.delete_all_cookies()
    for cookie in new_cookies:
        driver.add_cookie({
            'name': cookie['name'],
            'value': cookie['value'],
            'domain': '.airasia.cn'
        })

压力测试结果

在模拟100次连续请求测试中:

  • Selenium方案成功率82%
  • Playwright方案成功率95%
  • 平均耗时差异达3.7倍

最终建议:对反爬机制较强的目标网站优先采用Playwright方案,配合完善的代理管理和请求特征模拟,可有效获取动态加载内容。保留Selenium方案用于特殊验证场景突破。

相关推荐
爱敲代码的菜菜4 小时前
【测试】自动化测试
css·selenium·测试工具·junit·自动化·xpath
123过去12 小时前
wireshark使用教程
linux·网络·测试工具·wireshark
123过去12 小时前
hexinject使用教程
linux·网络·测试工具
测试199812 小时前
功能测试、自动化测试、性能测试的区别?
自动化测试·软件测试·python·功能测试·测试工具·性能测试·安全性测试
爱敲代码的菜菜14 小时前
【测试】Selenium
selenium·测试工具·xpath·webdriver·cssselector
shughui1 天前
Fiddler下载、安装、使用、汉化,详细图文教程(2026附安装包)
前端·测试工具·fiddler
若惜1 天前
selenium自动化测试web自动化测试 框架封装Pom
前端·python·selenium
2501_915921431 天前
常用iOS性能测试工具大全及使用指南
android·测试工具·ios·小程序·uni-app·cocoa·iphone
半个俗人2 天前
3.postman全局变量和环境变量
测试工具·postman