
Selenium 是 Web 自动化测试中最常用的工具之一。它提供了丰富的 API可以模拟用户对浏览器的各种操作包括元素定位、窗口控制、鼠标事件、键盘事件、信息获取以及等待机制等。本文将结合示例系统梳理 Selenium 的核心用法帮助你快速上手。一、使用 By 定位元素在 Selenium 中推荐使用By类配合find_element()方法定位元素语法格式如下pythonfind_element(By.定位方式, 定位名称)常见的定位方式及示例如下pythonfind_element(By.ID, kw) find_element(By.NAME, wd) find_element(By.CLASS_NAME, s_ipt) find_element(By.TAG_NAME, input) find_element(By.LINK_TEXT, 新闻) find_element(By.PARTIAL_LINK_TEXT, 新) find_element(By.XPATH, //*[classbg s_btn]) find_element(By.CSS_SELECTOR, span.bg s_btn_wrinput#su)注意旧版写法find_element_by_id()等已逐渐弃用建议统一使用By方式。二、控制浏览器和关闭操作1. 控制浏览器窗口大小pythondriver.set_window_size(宽度像素值, 高度像素值)2. 浏览器后退与前进pythondriver.back() # 后退 driver.forward() # 前进3. 刷新页面pythondriver.refresh()4. 关闭驱动pythondriver.close() # 只关闭当前自动化浏览器窗口chromedriver.exe 进程仍存在 driver.quit() # 退出驱动并关闭全部自动化浏览器窗口chromedriver.exe 进程被销毁三、鼠标事件Selenium 通过ActionChains类来模拟复杂的鼠标操作。首先需要引入pythonfrom selenium.webdriver.common.action_chains import ActionChains1. 左键单击pythonelement.click()2. 右键点击pythonelement driver.find_element(By.XXX, xx) ActionChains(driver).context_click(element).perform()3. 左键长按pythonelement driver.find_element(By.XXX, xx) ActionChains(driver).click_and_hold(element).perform()4. 鼠标悬停pythonelement driver.find_element(By.XXX, xx) ActionChains(driver).move_to_element(element).perform()练习悬停百度首页的“设置”链接。5. 鼠标双击pythonelement driver.find_element(By.XXX, xx) ActionChains(driver).double_click(element).perform()6. 鼠标拖放pythonsource driver.find_element(By.XXX, xx) target driver.find_element(By.XXX, xx) ActionChains(driver).drag_and_drop(source, target).perform()练习地址菜鸟教程在线编辑器四、键盘事件键盘操作需要引入Keys模块pythonfrom selenium.webdriver.common.keys import Keys1. 输入内容pythondriver.find_element(By.ID, kw).send_keys(seleniumm)2. 退格键删除pythondriver.find_element(By.ID, kw).send_keys(Keys.BACK_SPACE)3. 输入空格pythondriver.find_element(By.ID, kw).send_keys(Keys.SPACE)4. 组合键全选pythondriver.find_element(By.ID, kw).send_keys(Keys.CONTROL, a)常用的键盘操作还包括Keys.ENTER、Keys.TAB、Keys.ESCAPE等可根据需要组合使用。五、获得信息1. 获取当前页面 titlepythondriver.title2. 获取当前页面 URLpythondriver.current_url3. 获取标签的文本pythondriver.find_element(By.ID, kw).text4. 获取标签的属性标签的属性可通过 Chrome 开发工具的 Properties 标签查看。get_property()精确匹配元素标签的属性不能模糊匹配不推荐。get_attribute()模糊匹配元素标签的属性可获取包含属性如 class 属性和大小写模糊匹配的属性推荐使用。pythonelement.get_attribute(class)六、设置元素等待显式等待等待某个条件成立时继续执行否则在达到最大时长时抛出超时异常。pythonfrom selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By element WebDriverWait(driver, 5, 0.5).until( EC.presence_of_element_located((By.ID, kw)) ) element.send_keys(selenium)上述代码表示每 0.5 秒检查一次最多等待 5 秒直到 ID 为kw的元素出现在 DOM 中。七、总结本文整理了 Selenium 中常用的元素定位、浏览器控制、鼠标事件、键盘事件、信息获取和等待机制。掌握这些基础操作后你可以编写出稳定、高效的 Web 自动化脚本。在实际项目中建议优先使用By定位方式复杂交互使用ActionChains合理使用显式等待避免硬性休眠获取属性时优先选择get_attribute()。希望这篇博客能帮助你快速回顾和运用 Selenium 的核心功能。动手练习一遍效果更佳