阶段一:环境准备与基础操作
1.1 安装工具库
pip install selenium
pip install pyautogui
1.2 浏览器驱动下载
- 下载对应浏览器版本的驱动(如ChromeDriver)
- 将驱动文件放在Python安装目录或系统PATH路径中
阶段二:Selenium基础操作
2.1 启动浏览器并打开网页
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.quit()
2.2 元素定位与操作
search_box = driver.find_element(By.ID, "kw")
search_box.send_keys("Python自动化测试")
search_button = driver.find_element(By.NAME, "wd")
search_button.click()
element = driver.find_element(By.XPATH, "//input[@class='s_ipt']")
阶段三:进阶操作
3.1 处理弹窗和窗口切换
alert = driver.switch_to.alert
alert.accept()
for handle in driver.window_handles:
driver.switch_to.window(handle)
3.2 显式等待(解决元素加载问题)
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "element_id"))
)
阶段四:实际案例 - 电商网站自动化测试
4.1 模拟登录流程
def test_login():
driver.get("https://www.example.com/login")
driver.find_element(By.ID, "username").send_keys("test_user")
driver.find_element(By.ID, "password").send_keys("password123")
driver.find_element(By.XPATH, "//button[text()='登录']").click()
assert "我的账户" in driver.title
4.2 模拟购物流程
def test_shopping():
driver.find_element(By.NAME, "q").send_keys("手机")
driver.find_element(By.CLASS_NAME, "search-btn").click()
driver.find_element(By.XPATH, "(//a[contains(text(),'加入购物车')])[1]").click()
driver.find_element(By.LINK_TEXT, "去结算").click()
assert "订单确认" in driver.page_source
阶段五:PyAutoGUI桌面自动化
5.1 基础鼠标键盘操作
import pyautogui
pyautogui.moveTo(100, 200, duration=1)
pyautogui.click()
pyautogui.typewrite("Hello, PyAutoGUI!", interval=0.1)
pyautogui.hotkey('ctrl', 'c')
5.2 图像识别点击
button_location = pyautogui.locateOnScreen('button.png')
if button_location:
pyautogui.click(button_location)
阶段六:最佳实践与调试
6.1 使用Page Object模式(提高代码复用性)
class LoginPage:
def __init__(self, driver):
self.driver = driver
self.username_field = (By.ID, "username")
self.password_field = (By.ID, "password")
self.login_button = (By.XPATH, "//button[text()='登录']")
def login(self, username, password):
self.driver.find_element(*self.username_field).send_keys(username)
self.driver.find_element(*self.password_field).send_keys(password)
self.driver.find_element(*self.login_button).click()
6.2 错误处理与截图
try:
driver.find_element(By.ID, "non-existent-element").click()
except NoSuchElementException:
driver.save_screenshot("error.png")
阶段七:扩展学习方向
- Appium:移动端自动化测试
- PyTest:测试框架集成
- Headless模式:无界面浏览器测试
options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)