Selenium Web 自动化测试教程
Selenium 是历史最悠久、生态最丰富的 Web 自动化测试框架,支持 Python、Java、JavaScript、C# 等多种编程语言,能够驱动 Chrome、Firefox、Edge 等主流浏览器。在搬瓦工 VPS 上部署 Selenium 可以实现持续集成测试、网页监控和自动化操作。本教程以 Python + Chrome 为例进行讲解。
一、环境准备
- 操作系统:Ubuntu 20.04+(推荐 Ubuntu 22.04)。
- 内存:至少 1GB,建议 2GB 以上。
- Python:3.8 以上版本。
二、安装 Chrome 浏览器
2.1 安装 Google Chrome
apt update && apt upgrade -y
wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | gpg --dearmor -o /usr/share/keyrings/google-chrome.gpg
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/google-chrome.gpg] http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list
apt update
apt install google-chrome-stable -y
验证安装:
google-chrome --version
2.2 安装 ChromeDriver
Selenium 4 可以自动管理 ChromeDriver,也可以手动安装:
pip install webdriver-manager
三、安装 Selenium
mkdir -p /opt/selenium-project && cd /opt/selenium-project
python3 -m venv venv
source venv/bin/activate
pip install selenium webdriver-manager
四、基础用法
4.1 启动浏览器
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# 配置无头模式
options = Options()
options.add_argument('--headless=new')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--window-size=1920,1080')
# 自动下载对应版本的 ChromeDriver
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://example.com')
print(f'页面标题: {driver.title}')
driver.quit()
4.2 元素定位与交互
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
options = Options()
options.add_argument('--headless=new')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://example.com/login')
# 等待元素出现并填写表单
wait = WebDriverWait(driver, 10)
username = wait.until(EC.presence_of_element_located((By.ID, 'username')))
username.send_keys('myuser')
password = driver.find_element(By.ID, 'password')
password.send_keys('mypassword')
# 点击登录
login_btn = driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]')
login_btn.click()
# 等待页面加载
wait.until(EC.url_changes('https://example.com/login'))
print(f'登录后 URL: {driver.current_url}')
driver.quit()
4.3 截图保存
driver.get('https://example.com')
driver.save_screenshot('page.png')
# 对特定元素截图
element = driver.find_element(By.ID, 'main-content')
element.screenshot('element.png')
五、高级功能
5.1 执行 JavaScript
# 滚动页面到底部
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
# 获取页面高度
height = driver.execute_script('return document.body.scrollHeight;')
print(f'页面高度: {height}px')
# 修改元素属性
driver.execute_script(
'document.querySelector("#element").style.display = "block";'
)
5.2 Cookie 管理
# 获取所有 Cookie
cookies = driver.get_cookies()
for cookie in cookies:
print(f'{cookie["name"]}: {cookie["value"]}')
# 添加 Cookie
driver.add_cookie({'name': 'session_id', 'value': 'abc123', 'domain': '.example.com'})
# 删除 Cookie
driver.delete_cookie('session_id')
driver.delete_all_cookies()
5.3 多窗口和标签页
# 打开新标签页
driver.execute_script("window.open('https://example.com/page2', '_blank');")
# 切换到新标签页
handles = driver.window_handles
driver.switch_to.window(handles[-1])
print(f'新标签页: {driver.title}')
# 切回原始标签页
driver.switch_to.window(handles[0])
六、使用 Docker 部署 Selenium Grid
Selenium Grid 支持分布式测试,使用 Docker 部署非常方便。首先确保已安装 Docker:
mkdir -p /opt/selenium-grid && cd /opt/selenium-grid
cat > docker-compose.yml <<'EOF'
version: '3.8'
services:
selenium-hub:
image: selenium/hub:latest
container_name: selenium-hub
restart: always
ports:
- "4442:4442"
- "4443:4443"
- "4444:4444"
chrome-node:
image: selenium/node-chrome:latest
container_name: chrome-node
restart: always
depends_on:
- selenium-hub
environment:
- SE_EVENT_BUS_HOST=selenium-hub
- SE_EVENT_BUS_PUBLISH_PORT=4442
- SE_EVENT_BUS_SUBSCRIBE_PORT=4443
- SE_NODE_MAX_SESSIONS=4
shm_size: '2g'
firefox-node:
image: selenium/node-firefox:latest
container_name: firefox-node
restart: always
depends_on:
- selenium-hub
environment:
- SE_EVENT_BUS_HOST=selenium-hub
- SE_EVENT_BUS_PUBLISH_PORT=4442
- SE_EVENT_BUS_SUBSCRIBE_PORT=4443
- SE_NODE_MAX_SESSIONS=4
shm_size: '2g'
EOF
docker compose up -d
连接 Selenium Grid 运行测试:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless=new')
driver = webdriver.Remote(
command_executor='http://localhost:4444/wd/hub',
options=options
)
driver.get('https://example.com')
print(f'通过 Grid 访问: {driver.title}')
driver.quit()
七、与 pytest 集成
pip install pytest
创建 test_example.py 测试文件:
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
@pytest.fixture
def driver():
options = Options()
options.add_argument('--headless=new')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
service = Service(ChromeDriverManager().install())
drv = webdriver.Chrome(service=service, options=options)
yield drv
drv.quit()
def test_page_title(driver):
driver.get('https://example.com')
assert 'Example' in driver.title
def test_page_content(driver):
driver.get('https://example.com')
body = driver.find_element('tag name', 'body')
assert body.text != ''
运行测试:
pytest test_example.py -v
八、常见问题
Chrome 崩溃或无法启动
在 VPS 上需要增加共享内存大小:
mount -o remount,size=2G /dev/shm
ChromeDriver 版本不匹配
使用 webdriver-manager 可以自动匹配版本。如果手动安装,确保 ChromeDriver 版本与 Chrome 版本一致。
总结
Selenium 是成熟可靠的 Web 自动化测试框架,在搬瓦工 VPS 上可以搭建完整的测试环境。结合 Docker 部署 Selenium Grid 可以实现多浏览器并行测试。选购搬瓦工 VPS 请参考 全部方案,购买时使用优惠码 NODESEEK2026 可享受 6.77% 折扣。相关教程:Playwright 教程、Puppeteer 教程。