Selenium 核心基础类

Selenium 的核心类是其实现浏览器自动化的基础,主要通过 WebDriver 接口和相关的工具类完成操作。以下是 Python 版 Selenium 中最关键的核心类及其作用详解:

1. WebDriver 类

作用:控制浏览器实例,提供与浏览器交互的顶层 API。

模块selenium.webdriver

常用子类

  • Chrome:Chrome 浏览器驱动
  • Firefox:Firefox 浏览器驱动
  • Edge:Edge 浏览器驱动
  • Safari:Safari 浏览器驱动

核心方法

  • get(url):打开指定 URL
  • find_element(by, value):定位单个元素
  • find_elements(by, value):定位多个元素
  • execute_script(script):执行 JavaScript
  • quit():关闭浏览器并释放驱动资源
  • switch_to:切换上下文(如 iframe、弹窗)

示例

from selenium import webdriver

driver = webdriver.Chrome()  # 创建 Chrome 浏览器实例
driver.get("https://www.baidu.com")
driver.quit()

2. WebElement 类

作用:表示页面上的元素(如按钮、输入框),提供元素操作的方法。

模块selenium.webdriver.remote.webelement.WebElement

核心方法

  • click():点击元素
  • send_keys(text):输入文本
  • text:获取元素文本内容
  • get_attribute(name):获取元素属性值
  • is_displayed():判断元素是否可见
  • find_element(by, value):在当前元素下查找子元素
search_input = driver.find_element(By.ID, "kw")
search_input.send_keys("Selenium")
search_input.submit()  # 提交表单

3. By 类

作用:定义元素定位策略(如 ID、XPath、CSS 选择器等)。

模块selenium.webdriver.common.by.By

常用定位策略

  • By.ID:通过元素的 ID 属性定位
  • By.NAME:通过元素的 Name 属性定位
  • By.XPATH:通过 XPath 表达式定位
  • By.CSS_SELECTOR:通过 CSS 选择器定位
  • By.CLASS_NAME:通过元素的 Class 名称定位
  • By.TAG_NAME:通过标签名称定位

示例

from selenium.webdriver.common.by import By

element = driver.find_element(By.XPATH, "//button[@type='submit']")

4. WebDriverWait 与 expected_conditions

作用:实现显式等待,解决页面异步加载问题。

模块

  • selenium.webdriver.support.ui.WebDriverWait
  • selenium.webdriver.support.expected_conditions (简称 EC)

核心方法

  • until(method):等待直到条件满足
  • until_not(method):等待直到条件不满足

常用条件(EC 类)

  • presence_of_element_located:元素存在于 DOM
  • visibility_of_element_located:元素可见
  • element_to_be_clickable:元素可点击
  • title_contains(text):页面标题包含指定文本

示例

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.ID, "dynamic-element"))
)

5. ActionChains 类

作用:模拟复杂用户交互(如鼠标悬停、拖放、右键菜单)。

模块selenium.webdriver.common.action_chains.ActionChains

核心方法

  • click(element):点击元素
  • drag_and_drop(source, target):拖放元素
  • move_to_element(element):鼠标悬停
  • context_click(element):右键点击
  • send_keys(text):输入文本

示例

from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)
menu = driver.find_element(By.ID, "menu")
submenu = driver.find_element(By.ID, "submenu")
actions.move_to_element(menu).click(submenu).perform()

6. Options 类

作用:配置浏览器启动选项(如无头模式、代理、扩展)。

模块

  • Chrome:selenium.webdriver.chrome.options.Options
  • Firefox:selenium.webdriver.firefox.options.Options

常用配置

  • 无头模式:add_argument("--headless")
  • 禁用 GPU:add_argument("--disable-gpu")
  • 设置代理:add_argument("--proxy-server=http://1.2.3.4:8080")
  • 加载扩展:add_extension("extension.crx")

示例

from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)

7. Alert 类

作用:处理 JavaScript 弹窗(如警告框、确认框、提示框)。

模块selenium.webdriver.common.alert.Alert

核心方法

  • accept():确认弹窗
  • dismiss():取消弹窗
  • text:获取弹窗文本
  • send_keys(text):向提示框输入文本

示例

alert = driver.switch_to.alert
print(alert.text)
alert.accept()

8. Select 类

作用:操作下拉选择框(<select> 元素)。

模块selenium.webdriver.support.select.Select

核心方法

  • select_by_index(index):通过索引选择
  • select_by_value(value):通过值选择
  • select_by_visible_text(text):通过可见文本选择
  • deselect_all():取消所有选择(多选模式下)

示例

from selenium.webdriver.support.select import Select

dropdown = Select(driver.find_element(By.ID, "country"))
dropdown.select_by_visible_text("China")

9. JavaScriptExecutor 接口

作用:通过 execute_script() 直接执行 JavaScript 代码。

实现类WebDriver 类已实现该接口。

常用场景

  • 修改元素属性
  • 滚动页面
  • 处理复杂的 DOM 操作

示例

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.execute_script("arguments[0].style.border='3px solid red';", element)

10. 异常类

作用:处理自动化过程中的错误。

核心异常

  • NoSuchElementException:元素未找到
  • TimeoutException:等待超时
  • ElementNotInteractableException:元素不可交互
  • StaleElementReferenceException:元素引用失效
  • WebDriverException:通用 WebDriver 错误

示例

from selenium.common.exceptions import NoSuchElementException

try:
    driver.find_element(By.ID, "non-existent-element")
except NoSuchElementException:
    print("元素不存在!")

总结

WebDriver

浏览器控制

打开页面、导航、关闭浏览器

WebElement

元素操作

输入文本、点击按钮

By

元素定位策略

使用 ID/XPath 定位元素

WebDriverWait

显式等待

处理动态加载元素

ActionChains

复杂交互模拟

拖放、右键菜单

Options

浏览器配置

无头模式、代理设置

Alert

弹窗处理

确认警告框

Select

下拉框操作

选择国家/地区

JavaScriptExecutor

执行 JavaScript

页面滚动、修改 DOM

异常类

错误处理

捕获元素定位失败

掌握这些核心类及其方法,可以高效编写稳定、灵活的浏览器自动化脚本。

进阶高级测试工程师 文章被收录于专栏

《高级软件测试工程师》专栏旨在为测试领域的从业者提供深入的知识和实践指导,帮助大家从基础的测试技能迈向高级测试专家的行列。 在本专栏中,主要涵盖的内容: 1. 如何设计和实施高效的测试策略; 2. 掌握自动化测试、性能测试和安全测试的核心技术; 3. 深入理解测试驱动开发(TDD)和行为驱动开发(BDD)的实践方法; 4. 测试团队的管理和协作能力。 ——For.Heart

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务