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

本文涉及的产品
实时数仓Hologres,5000CU*H 100GB 3个月
实时计算 Flink 版,5000CU*H 3个月
智能开放搜索 OpenSearch行业算法版,1GB 20LCU 1个月
简介: 本项目旨在解决亚航航班数据采集中的反爬挑战。初期使用Selenium遇到Cloudflare验证,后切换至Playwright仍触发反爬机制。通过引入代理IP轮换和UA策略,最终实现双方案并通过压力测试。Selenium适合模拟真人操作,而Playwright在执行速度和自动等待机制上表现更优,成功率高达95%。建议对强反爬网站优先采用Playwright,并配合完善的代理管理和请求特征模拟。

方案进程

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 | 双方案完整实现并通过压力测试
AI 代码解读

故障场景分析

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

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()
AI 代码解读

2. 反爬机制突破分析

通过Wireshark抓包发现:

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

架构改进方案

双引擎解决方案对比实现

# 公共配置参数
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()
AI 代码解读

技术方案对比

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

架构优化建议

  1. IP轮换策略:使用亿牛云代理服务实现每5次请求更换出口IP
  2. 混合验证突破
    • 首请求使用Selenium模拟真人操作
    • 后续数据采集使用Playwright提升效率
  3. 动态Cookie管理
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'
        })
AI 代码解读

压力测试结果

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

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

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

目录
打赏
0
1
1
0
203
分享
相关文章
Appium问题解决方案(8)- selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred while processing the command. Original error: Could not sign with default certificate.
Appium问题解决方案(8)- selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred while processing the command. Original error: Could not sign with default certificate.
1204 0
Appium问题解决方案(8)- selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred while processing the command. Original error: Could not sign with default certificate.
Selenium与WebDriver:Errno 8 Exec格式错误的多种解决方案
本文讨论了在使用Selenium和WebDriver自动化测试时常见的执行格式错误(Errno 8 Exec format error)问题。错误通常发生在运行ChromeDriver时,与兼容性或路径配置有关。文章提供了多种解决方案,包括手动更改路径、更新或重新安装webdriver-manager包、下载特定版本的ChromeDriver、修改driver_cache.py文件。此外,还介绍了如何结合代理IP技术使用Selenium进行网页抓取,以提高效率和成功率。示例代码展示了如何配置代理IP并使用Selenium访问网站。通过这些方法,用户可以有效解决执行格式错误,并提高网页自动化测试
1031 1
Selenium与WebDriver:Errno 8 Exec格式错误的多种解决方案
使用Selenium调试Edge浏览器的常见问题与解决方案
在互联网数据采集领域,Selenium常用于自动化网页爬取。针对使用Edge浏览器时遇到的启动远程调试失败、访问受限及代理IP设置等问题,本文提供了解决方案。通过特定命令启动Edge的远程调试模式,并利用Python脚本配合Selenium库,可实现代理IP、User-Agent的设定及Cookie管理等高级功能,有效提升爬虫稳定性和隐蔽性。遵循步骤配置后,即可顺畅执行自动化测试任务。
1544 1
使用Selenium调试Edge浏览器的常见问题与解决方案
scrapy_selenium的常见问题和解决方案
scrapy_selenium是一个结合了scrapy和selenium的库,可以让我们使用selenium的webdriver来控制浏览器进行动态网页的爬取。但是在使用scrapy_selenium的过程中,我们可能会遇到一些问题,比如如何设置代理、如何处理反爬、如何优化性能等。本文将介绍一些scrapy_selenium的常见问题和解决方案,希望对你有所帮助。
442 0
scrapy_selenium的常见问题和解决方案
|
10月前
|
Linux中使用selenium截图的文字变为方框的解决方案
Linux中使用selenium截图的文字变为方框的解决方案
182 1
selenium webdriver执行远程 第三方js解决方案
selenium webdriver执行远程 第三方js解决方案
123 0
selenium webdriver执行远程 第三方js解决方案
Selenium在Win10下IE浏览器遇到的白屏初始页面解决方案
开发环境:Win10+Python3.5+Selenium+IE11硬件环境:联想MIIX700语言环境:English(US)在做数据爬取得时候,发现IE Driver出现白屏,跟着提示:“This is the initial start page for the WebDriver server“几经寻找,解决了问题。
2119 0
Appium问题解决方案(5)- selenium.common.exceptions.InvalidSelectorException: Message: Locator Strategy 'name' is not supported for this session
Appium问题解决方案(5)- selenium.common.exceptions.InvalidSelectorException: Message: Locator Strategy 'name' is not supported for this session
516 0
Appium问题解决方案(5)- selenium.common.exceptions.InvalidSelectorException: Message: Locator Strategy 'name' is not supported for this session
Python+selenium自动化:页面加载慢、超时加载情况下内容已经加载完毕的快速执行脚本解决方案,页面加载时间过长优化方案
Python+selenium自动化:页面加载慢、超时加载情况下内容已经加载完毕的快速执行脚本解决方案,页面加载时间过长优化方案
1582 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等