Selenium 查找页面元素的方式

Selenium 查找页面元素的方式

Selenium 提供了多种方法来查找网页中的元素,以下是主要的定位方式:

基本定位方式

  1. 通过ID定位

    python 复制代码
    driver.find_element(By.ID, "element_id")
  2. 通过Name定位

    python 复制代码
    driver.find_element(By.NAME, "element_name")
  3. 通过Class Name定位

    python 复制代码
    driver.find_element(By.CLASS_NAME, "class_name")
  4. 通过Tag Name定位

    python 复制代码
    driver.find_element(By.TAG_NAME, "tag_name")
  5. 通过Link Text定位(精确匹配)

    python 复制代码
    driver.find_element(By.LINK_TEXT, "链接文本")
  6. 通过Partial Link Text定位(部分匹配)

    python 复制代码
    driver.find_element(By.PARTIAL_LINK_TEXT, "部分链接文本")

CSS 选择器定位

python 复制代码
driver.find_element(By.CSS_SELECTOR, "css_selector")

示例:

  • "#id" - 通过ID
  • ".class" - 通过类名
  • "div > input" - 子元素
  • "input[type='text']" - 属性选择器

XPath 定位

python 复制代码
driver.find_element(By.XPATH, "xpath_expression")

示例:

  • "//input" - 所有input元素
  • "//div[@id='main']" - 特定属性的div
  • "//a[contains(text(),'登录')]" - 包含特定文本的链接

查找多个元素

使用find_elements(注意复数形式)返回匹配的所有元素列表:

python 复制代码
elements = driver.find_elements(By.CSS_SELECTOR, ".list-item")

相对定位(Selenium 4新增)

Selenium 4 引入了相对定位器:

python 复制代码
from selenium.webdriver.support.relative_locator import locate_with

password = driver.find_element(By.ID, "password")
email = driver.find_element(locate_with(By.TAG_NAME, "input").above(password))

相对定位方法包括:above(), below(), to_left_of(), to_right_of(), near()

最佳实践

  1. 优先使用ID定位,因为ID通常是唯一的且效率最高
  2. 当ID不可用时,考虑使用CSS选择器
  3. XPath功能强大但执行较慢,应谨慎使用
  4. 对于动态元素,考虑使用显式等待结合定位策略

示例代码

python 复制代码
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

driver = webdriver.Chrome()
driver.get("https://example.com")

# 使用显式等待定位元素
element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "dynamic-element"))
)

# 使用CSS选择器
submit_button = driver.find_element(By.CSS_SELECTOR, "button.submit-btn")

# 使用XPath
link = driver.find_element(By.XPATH, "//a[contains(@href, 'logout')]")

记得在使用完WebDriver后调用driver.quit()来关闭浏览器和释放资源。

支付宝这一次力度够大的啊,后台看到有人居然领了 20 元,你也来试试

相关推荐
卓码软件测评9 小时前
第三方应用测试:【移动应用后端API自动化测试:Postman与Newman的集成】
功能测试·测试工具·测试用例·可用性测试
青草地溪水旁19 小时前
tcpdump调试
网络·测试工具·tcpdump
深蓝电商API2 天前
实战破解前端渲染:当 Requests 无法获取数据时(Selenium/Playwright 入门)
前端·python·selenium·playwright
卓码软件测评2 天前
第三方软件验收测试:【AutoIt与Selenium结合测试文件上传/下载等Windows对话框】
windows·功能测试·selenium·测试工具·性能优化·可用性测试
最好的我们!2 天前
解决selenium的EdgeOptions addArguments is not supported问题
selenium·测试工具
万粉变现经纪人3 天前
如何解决 pip install 安装报错 ImportError: cannot import name ‘xxx’ from ‘yyy’ 问题
python·selenium·测试工具·flask·scikit-learn·fastapi·pip
gc_22993 天前
学习Python中Selenium模块的基本用法(18:使用ActionChains操作鼠标)
python·selenium
卓码软件测评3 天前
第三方软件登记测试机构:【软件登记测试机构HTML5测试技术】
前端·功能测试·测试工具·html·测试用例·html5
可可南木3 天前
ICT 数字测试原理 3 --SAFETYGUARD 文件
开发语言·测试工具·pcb工艺
卓码软件测评3 天前
第三方软件测试公司:【Gatling基于Scala的开源高性能负载测试工具】
测试工具·开源·scala·压力测试·可用性测试·第三方软件测试