Selenium 安装与配置 #

环境要求 #

在开始安装 Selenium 之前,请确保系统满足以下要求:

基础环境 #

text
┌─────────────────────────────────────────────────────────────┐
│                      环境要求                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  编程语言:                                                   │
│  • Python 3.7+                                              │
│  • Java 8+                                                  │
│  • Node.js 12+                                              │
│  • C# .NET Core 3.1+                                        │
│                                                             │
│  浏览器:                                                     │
│  • Chrome 90+                                               │
│  • Firefox 90+                                              │
│  • Edge 90+                                                 │
│  • Safari 14+ (macOS)                                       │
│                                                             │
│  操作系统:                                                   │
│  • Windows 10/11                                            │
│  • macOS 10.15+                                             │
│  • Linux (Ubuntu 20.04+)                                    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Python 环境安装 #

1. 安装 Python #

bash
# macOS (使用 Homebrew)
brew install python@3.11

# Ubuntu/Debian
sudo apt update
sudo apt install python3.11 python3.11-venv python3-pip

# Windows
# 从 python.org 下载安装包

2. 创建虚拟环境 #

bash
# 创建虚拟环境
python -m venv selenium-env

# 激活虚拟环境
# macOS/Linux
source selenium-env/bin/activate

# Windows
selenium-env\Scripts\activate

3. 验证 Python 环境 #

bash
python --version
# Python 3.11.x

pip --version
# pip 23.x.x from ...

安装 Selenium #

使用 pip 安装 #

bash
# 安装最新版本
pip install selenium

# 安装指定版本
pip install selenium==4.15.0

# 升级到最新版本
pip install --upgrade selenium

验证安装 #

bash
# 查看安装版本
pip show selenium

# 输出示例
# Name: selenium
# Version: 4.15.0
# Summary: Python bindings for Selenium
python
# Python 中验证
import selenium
print(selenium.__version__)
# 4.15.0

浏览器驱动安装 #

方式一:自动管理驱动(推荐) #

Selenium 4.x 内置了 Selenium Manager,可以自动下载和管理浏览器驱动:

python
from selenium import webdriver

# 无需手动配置,自动管理驱动
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
print(driver.title)
driver.quit()

方式二:使用 webdriver-manager #

使用第三方库管理驱动:

bash
# 安装 webdriver-manager
pip install webdriver-manager
python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager

# Chrome 浏览器
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

# Firefox 浏览器
driver = webdriver.Firefox(service=Service(GeckoDriverManager().install()))

# Edge 浏览器
from webdriver_manager.microsoft import EdgeChromiumDriverManager
driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install()))

方式三:手动安装驱动 #

ChromeDriver 安装 #

text
┌─────────────────────────────────────────────────────────────┐
│                  ChromeDriver 安装步骤                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 查看浏览器版本                                           │
│     chrome://settings/help                                  │
│                                                             │
│  2. 下载对应版本驱动                                         │
│     https://chromedriver.chromium.org/downloads             │
│     或                                                      │
│     https://googlechromelabs.github.io/chrome-for-testing/  │
│                                                             │
│  3. 解压并配置                                               │
│     • macOS/Linux: /usr/local/bin/                          │
│     • Windows: 添加到 PATH 环境变量                          │
│                                                             │
│  4. 验证安装                                                 │
│     chromedriver --version                                  │
│                                                             │
└─────────────────────────────────────────────────────────────┘
python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# 指定驱动路径
service = Service('/path/to/chromedriver')
driver = webdriver.Chrome(service=service)

GeckoDriver 安装(Firefox) #

bash
# macOS
brew install geckodriver

# Ubuntu/Debian
sudo apt install firefox-geckodriver

# 手动下载
# https://github.com/mozilla/geckodriver/releases
python
from selenium import webdriver
from selenium.webdriver.firefox.service import Service

service = Service('/path/to/geckodriver')
driver = webdriver.Firefox(service=service)

EdgeDriver 安装 #

bash
# Windows 通常已包含
# 或从以下地址下载:
# https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
python
from selenium import webdriver
from selenium.webdriver.edge.service import Service

service = Service('/path/to/msedgedriver')
driver = webdriver.Edge(service=service)

浏览器配置 #

Chrome 配置选项 #

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

options = Options()

# 无头模式
options.add_argument('--headless')

# 禁用 GPU
options.add_argument('--disable-gpu')

# 设置窗口大小
options.add_argument('--window-size=1920,1080')

# 禁用沙箱
options.add_argument('--no-sandbox')

# 禁用开发者模式
options.add_argument('--disable-dev-shm-usage')

# 禁用自动化检测
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomationExtension', False)

# 禁用图片加载(提高速度)
prefs = {'profile.managed_default_content_settings.images': 2}
options.add_experimental_option('prefs', prefs)

# 设置代理
options.add_argument('--proxy-server=http://proxy.example.com:8080')

# 设置 User-Agent
options.add_argument('--user-agent=Mozilla/5.0 ...')

# 创建驱动
driver = webdriver.Chrome(options=options)

Firefox 配置选项 #

python
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service

options = Options()

# 无头模式
options.add_argument('--headless')

# 设置日志级别
options.set_preference('webdriver.log.level', 'ERROR')

# 设置下载目录
options.set_preference('browser.download.folderList', 2)
options.set_preference('browser.download.dir', '/path/to/download')

# 禁用图片
options.set_preference('permissions.default.image', 2)

# 设置代理
options.set_preference('network.proxy.type', 1)
options.set_preference('network.proxy.http', 'proxy.example.com')
options.set_preference('network.proxy.http_port', 8080)

driver = webdriver.Firefox(options=options)

Edge 配置选项 #

python
from selenium import webdriver
from selenium.webdriver.edge.options import Options

options = Options()

# 无头模式
options.add_argument('--headless')

# 其他选项与 Chrome 类似
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')

driver = webdriver.Edge(options=options)

项目结构 #

推荐项目结构 #

text
selenium-project/
├── drivers/                  # 驱动目录(可选)
│   ├── chromedriver
│   └── geckodriver
├── tests/                    # 测试用例
│   ├── __init__.py
│   ├── conftest.py          # pytest 配置
│   ├── test_login.py
│   └── test_search.py
├── pages/                    # 页面对象
│   ├── __init__.py
│   ├── base_page.py
│   ├── login_page.py
│   └── home_page.py
├── utils/                    # 工具函数
│   ├── __init__.py
│   └── helpers.py
├── config/                   # 配置文件
│   ├── __init__.py
│   └── settings.py
├── reports/                  # 测试报告
├── screenshots/              # 截图目录
├── requirements.txt          # 依赖文件
└── pytest.ini               # pytest 配置

requirements.txt #

text
selenium==4.15.0
webdriver-manager==4.0.1
pytest==7.4.3
pytest-html==4.1.1
pytest-xdist==3.5.0
allure-pytest==2.13.2

配置文件示例 #

python
# config/settings.py
from dataclasses import dataclass
from typing import Optional

@dataclass
class BrowserConfig:
    name: str = "chrome"
    headless: bool = False
    window_width: int = 1920
    window_height: int = 1080
    implicit_wait: int = 10
    page_load_timeout: int = 30
    script_timeout: int = 30

@dataclass
class AppConfig:
    base_url: str = "https://example.com"
    username: str = "test_user"
    password: str = "test_password"

@dataclass
class Config:
    browser: BrowserConfig = BrowserConfig()
    app: AppConfig = AppConfig()
    screenshot_dir: str = "./screenshots"
    report_dir: str = "./reports"

config = Config()

编写第一个脚本 #

基础示例 #

python
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_baidu_search():
    driver = webdriver.Chrome()
    
    try:
        driver.get("https://www.baidu.com")
        
        search_box = driver.find_element(By.ID, "kw")
        search_box.send_keys("Selenium")
        
        search_button = driver.find_element(By.ID, "su")
        search_button.click()
        
        assert "Selenium" in driver.title
        
    finally:
        driver.quit()

if __name__ == "__main__":
    test_baidu_search()

使用配置的示例 #

python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from config.settings import config

def create_driver():
    options = Options()
    
    if config.browser.headless:
        options.add_argument('--headless')
    
    options.add_argument(f'--window-size={config.browser.window_width},{config.browser.window_height}')
    
    driver = webdriver.Chrome(
        service=Service(ChromeDriverManager().install()),
        options=options
    )
    
    driver.implicitly_wait(config.browser.implicit_wait)
    driver.set_page_load_timeout(config.browser.page_load_timeout)
    
    return driver

def test_example():
    driver = create_driver()
    
    try:
        driver.get(config.app.base_url)
        print(f"Page title: {driver.title}")
    finally:
        driver.quit()

常见问题排查 #

1. 驱动版本不匹配 #

text
错误信息:This version of ChromeDriver only supports Chrome version XX

解决方案:
1. 更新浏览器到最新版本
2. 或下载匹配的驱动版本
3. 或使用 webdriver-manager 自动管理

2. 驱动找不到 #

text
错误信息:'chromedriver' executable needs to be in PATH

解决方案:
1. 将驱动添加到系统 PATH
2. 或在代码中指定驱动路径
3. 或使用 Selenium Manager 自动管理

3. 权限问题(macOS/Linux) #

bash
# 给驱动添加执行权限
chmod +x /path/to/chromedriver

# macOS 可能需要允许运行
# 系统偏好设置 -> 安全性与隐私 -> 允许

4. SSL 证书问题 #

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

options = Options()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')

driver = webdriver.Chrome(options=options)

5. 连接超时 #

python
from selenium import webdriver

driver = webdriver.Chrome()

# 设置超时时间
driver.set_page_load_timeout(60)  # 页面加载超时
driver.set_script_timeout(30)      # 脚本执行超时

验证安装 #

完整验证脚本 #

python
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.firefox.options import Options as FirefoxOptions

def check_python_version():
    print(f"Python 版本: {sys.version}")
    assert sys.version_info >= (3, 7), "需要 Python 3.7+"

def check_selenium_version():
    import selenium
    print(f"Selenium 版本: {selenium.__version__}")

def test_chrome():
    print("\n测试 Chrome 浏览器...")
    options = Options()
    options.add_argument('--headless')
    
    try:
        driver = webdriver.Chrome(options=options)
        driver.get("https://www.baidu.com")
        print(f"✓ Chrome 测试成功: {driver.title}")
        driver.quit()
        return True
    except Exception as e:
        print(f"✗ Chrome 测试失败: {e}")
        return False

def test_firefox():
    print("\n测试 Firefox 浏览器...")
    options = FirefoxOptions()
    options.add_argument('--headless')
    
    try:
        driver = webdriver.Firefox(options=options)
        driver.get("https://www.baidu.com")
        print(f"✓ Firefox 测试成功: {driver.title}")
        driver.quit()
        return True
    except Exception as e:
        print(f"✗ Firefox 测试失败: {e}")
        return False

def main():
    print("=" * 50)
    print("Selenium 环境验证")
    print("=" * 50)
    
    check_python_version()
    check_selenium_version()
    
    chrome_ok = test_chrome()
    firefox_ok = test_firefox()
    
    print("\n" + "=" * 50)
    print("验证结果:")
    print(f"  Chrome: {'✓' if chrome_ok else '✗'}")
    print(f"  Firefox: {'✓' if firefox_ok else '✗'}")
    print("=" * 50)

if __name__ == "__main__":
    main()

下一步 #

环境配置完成后,接下来学习 基础使用 开始编写自动化脚本!

最后更新:2026-03-28