Selenium 零基础测开学习 25——UI 自动化_Selenium 进阶

EternalRights · 2026年04月13日 · 135 次阅读

前言

        Selenium 作为常春藤,进阶如同苍天大树。其基础可以回顾上一篇零基础测开学习 24——UI 自动化_Selenium 基础,而本篇将会是对于 Selenium 的更上一层楼,旨在拔高。


1.对抗反爬与检测

        现代网站的反爬机制日益精密。电商平台、金融系统、大型社交网络都有严格的机器人检测。以下技术能显著提高成功率,但没有任何方案是 100% 可靠的——这是一个持续攻防的过程。

基础级伪装

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options

options = ChromeOptions()
# 禁用自动化控制标志
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_argument("--disable-blink-features=AutomationControlled")
# 去除 webdriver 属性
options.add_argument("--disable-blink-features=AutomationControlled")
# 随机化窗口大小
options.add_argument("--window-size=1920,1080")

driver = Chrome(options=options)

进阶方案:undetected-chromedriver

注意:undetected-chromedriver 也在 Alumnium 的 WebVoyager 基准测试中被使用(针对 Google Search 等高防护站点)。

        对于需要更高隐蔽性的场景,undetected-chromedriver 是一个经过实践验证的选择。它通过补丁修改驱动二进制文件,能绕过大部分基础检测(Cloudflare、DataDome 等)。

import undetected_chromedriver as uc

driver = uc.Chrome()
driver.get("https://example.com")

代理与指纹协同

        配合高质量住宅代理(Residential Proxy)和动态 User-Agent,能进一步降低被检测的概率。这是"组合拳"——单一手段效果有限,多层叠加才有效。


2. Selenium Grid 4 与分布式测试

当测试用例突破千级大关,单机执行会成为明显的效率瓶颈。

核心架构

        Selenium Grid 4 基于纯容器化设计,原生支持 Docker Compose 和 Kubernetes。

生产级实践:K8s 弹性伸缩

        在 CI/CD 流水线中,通过 Kubernetes HPA(Horizontal Pod Autoscaler)根据队列深度自动伸缩 Grid 节点数量,实现按需测试:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: selenium-grid-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: selenium-node-chrome
  minReplicas: 2
  maxReplicas: 20
  metrics:
  - type: External
    external:
      metric:
        name: selenium_pending_requests
      target:
        type: AverageValue
        averageValue: "5"

现实建议

        对于中小型团队,直接使用云服务更划算。Sauce Labs 和 BrowserStack 提供了开箱即用的 Selenium Grid,运维成本为零。按需付费,避免自己维护 K8s 集群的复杂性。


深度集成:Chrome DevTools Protocol

        Selenium 4 允许直接调用 CDP,实现网络拦截、性能监控、模拟网络条件等常规 API 无法完成的功能。

import asyncio
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

async def monitor_network():
    # 创建带 CDP 的 driver
    options = Options()
    driver = webdriver.Chrome(options=options)

    try:
        # 获取 DevTools session
        async with driver.bidi_connection() as session:
            # 通过 WebSocket URL 创建 CDP session
            cdp_session = session.new_cdp_session("network")

            # 定义回调函数
            def on_response pending_task_info:
                url = pending_task_info.get("url", "")
                if "api/data" in url:
                    print(f"Intercepted: {url}")

            # 注册网络监听
            cdp_session.on("Network.requestWillBeSent", on_response)

            driver.get("https://example.com")
            await asyncio.sleep(2)

    finally:
        driver.quit()

asyncio.run(monitor_network())

常见 CDP 应用场景

常见 CDP 应用场景

场景 CDP 能力
Mock 接口响应 Fetch.enable() + Fetch.failRequest() / Fetch.fulfillRequest()
性能分析 Performance.enable() 获取指标
网络日志 Network.requestWillBeSent / Network.responseReceived
截取 HAR Network.enable() + 导出 JSON
模拟慢网 Network.emulateNetworkConditions()

后记

        Selenium 至此完结,如有更多疑惑可以参考Selenium 官方文档。后续笔者的 UI 自动化小合集会推出 Playwright 与 AI 驱动的 UI 自动化——Alumnium,尽请期待。

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册