UI自动化测试之Selenium元素定位8大方式

UI自动化测试之Selenium元素定位8大方式

Selenium 提供了多种元素定位方法,常用的有以下几种:

1、通过 ID 定位

方法:find_element(By.ID, "id_value")

**说明:**通过元素的 id 属性定位。

复制代码
from selenium.webdriver.common.by import By

element = driver.find_element(By.ID, "username")

2、通过 Name 定位

方法:find_element(By.NAME, "name_value")

**说明:**通过元素的 name 属性定位。

复制代码
element = driver.find_element(By.NAME, "password")

3、通过 Class Name 定位

方法:find_element(By.CLASS_NAME, "class_name")

**说明:**通过元素的 class 属性定位。

复制代码
element = driver.find_element(By.CLASS_NAME, "submit-btn")

4、通过 Tag Name 定位

方法:find_element(By.TAG_NAME, "tag_name")

**说明:**通过元素的标签名定位(如 <div>、<input> 等)。

复制代码
 element = driver.find_element(By.TAG_NAME, "input")

5、通过 CSS 选择器定位

方法:find_element(By.CSS_SELECTOR, "css_selector")

**说明:**通过 CSS 选择器定位元素。

复制代码
 element = driver.find_element(By.CSS_SELECTOR, "input#username")

6、通过 XPath 定位

方法:find_element(By.XPATH, "xpath_expression")

**说明:**通过 XPath 表达式定位元素。

复制代码
 element = driver.find_element(By.XPATH, "//input[@id='username']")

7、通过 Link Text 定位

方法:find_element(By.LINK_TEXT, "link_text")

**说明:**通过链接的文本内容定位(适用于 <a> 标签)。

复制代码
 element = driver.find_element(By.LINK_TEXT, "Click Here")

8、通过 Partial Link Text 定位

方法:find_element(By.PARTIAL_LINK_TEXT, "partial_link_text")

**说明:**通过链接的部分文本内容定位。

复制代码
 element = driver.find_element(By.PARTIAL_LINK_TEXT, "Click")
相关推荐
mewowaBc7 小时前
postman使用细则
测试工具·postman·偏差
光影62717 小时前
Unittest单元测试基础速记
测试工具·单元测试·json·测试覆盖率
oicola17 小时前
【UI动效】科幻风长任务进度动效设计方案
ui
xie881018021 天前
正则里的点号不匹配换行:多行模式的开关
运维·服务器·测试工具
xy34531 天前
Axure9.0 热区典型实战使用场景
ui·axure·原型·产品设计
2601_967987372 天前
Python在自动化测试中有哪些应用?
python自动化测试·selenium·appium·pytest·性能测试
东舟技术2 天前
从人工目检到AI视觉:智能座舱瞬态故障的自动化捕获与溯源
功能测试·测试工具·自动化
喜欢吃豆2 天前
我开源了 Agent UI Lab 用交互实验理解 AG-UI A2UI 与 MCP Apps
ui·开源·大模型·交互
染指11103 天前
158.Agent-LangGraph-子图(共享状态和不共享状态模式)
开发语言·人工智能·python·ui·agent·agents
小猿A3 天前
【2026最新】Apifox下载、配置、实战教程(附官网安装包)
测试工具