UI自动化:Python + Selenium4.6+版本 环境搭建

以下是 Python + Selenium 4.12+ 环境搭建 的详细步骤(无需手动下载浏览器驱动,利用 Selenium Manager 自动管理驱动):


1. 安装 Python

1.1 下载并安装 Python

1.2 验证 Python 安装

bash

复制

bash 复制代码
python --version  # 输出 Python 版本(如 Python 3.10+)
pip --version     # 输出 pip 版本

2. 安装 Selenium

2.1 安装最新版 Selenium

bash

复制

bash 复制代码
pip install selenium --upgrade  # 确保版本 ≥4.12.0

2.2 验证 Selenium 版本

bash

复制

bash 复制代码
pip show selenium  # 确认版本为 4.12+

3. 自动管理浏览器驱动(Selenium Manager)

Selenium 4.6+ 开始内置 Selenium Manager,能自动检测浏览器版本并下载匹配的驱动,无需手动操作!


4. 编写测试脚本

示例代码(以 Chrome 为例)

python

复制

python 复制代码
from selenium import webdriver

# 无需指定驱动路径,Selenium Manager 自动处理!
driver = webdriver.Chrome()  # 自动下载 chromedriver
driver.get("https://www.baidu.com")
print(driver.title)  # 输出页面标题
driver.quit()

支持的浏览器

  • Chromewebdriver.Chrome()

  • Firefoxwebdriver.Firefox()

  • Edgewebdriver.Edge()

  • Safariwebdriver.Safari()(仅 macOS)


5. 运行脚本

bash

复制

bash 复制代码
python test_selenium.py

首次运行效果

  1. Selenium Manager 自动检测本地浏览器版本。

  2. 下载对应的浏览器驱动(如 chromedriver)。

  3. 驱动默认保存路径:

    • Windows%USERPROFILE%\.cache\selenium\

    • macOS/Linux~/.cache/selenium/


6. 验证是否成功

  • 成功标志:自动打开浏览器并访问页面,无报错。

  • 失败排查

    • 确保浏览器已安装(如 Chrome/Firefox)。

    • 检查网络是否可访问国外资源(驱动默认从官方源下载)。

    • 若自动下载失败,可手动指定驱动路径(见下文备用方案)。


7. 进阶配置(可选)

7.1 自定义驱动缓存路径

通过环境变量指定驱动缓存位置:

bash

复制

bash 复制代码
# Windows
set SE_CACHE_PATH=C:\my_drivers

# macOS/Linux
export SE_CACHE_PATH=/path/to/my_drivers

7.2 手动指定浏览器路径

若浏览器未安装在默认位置:

python

复制

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

options = Options()
options.binary_location = "C:/Program Files/Google/Chrome/Application/chrome.exe"
driver = webdriver.Chrome(options=options)

8. 常见问题

Q1:自动下载驱动失败

  • 原因 :网络无法访问 https://googlechromelabs.github.io/chrome-for-testing/

  • 解决

    1. 手动下载驱动并放到缓存目录(路径见上文)。

    2. 或使用镜像源(需修改 Selenium Manager 源码,不推荐)。

Q2:浏览器版本太旧

  • 解决:升级浏览器到最新稳定版。

Q3:备用方案(兼容旧版写法)

若不信任自动下载,仍可手动指定驱动:

python

复制

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

service = Service(executable_path="C:/path/to/chromedriver.exe")
driver = webdriver.Chrome(service=service)
相关推荐
曲幽2 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程7 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪7 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook7 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田20 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python