Selenium Web元素定位方法

本文介绍了Selenium WebDriver提供的八种Web元素定位方法,包括ID、NAME、LinkText等,并通过Python示例代码展示了如何使用这些方法进行Web自动化测试。

Selenium是用于Web应用测试的自动化测试框架,可以实现跨浏览器和跨平台的Web自动化测试。Selenium通过使用WebDriver API来控制web浏览器,每个浏览器都都有一个特定的WebDriver 驱动,处理与Selenium和浏览器之间的通信。

实现Web页面自动化控制的先决条件是定位到正确的Web页面元素,WebDriver提供了8种不同的Web元素定位方法:

LocatorDescription
idID属性,最常用的定位方法,每个元素的id应该是唯一的
css selectorCSS 选择器
xpathxpath表达式定位元素
nameNAME属性,与id定位类似
link text仅用于超链接文本
partial link text使用方法和link text相同,partial link 只截取部分文字即可
tag name通过HTML标签名定位
class name使用类名定位,不能使用复合类名

ID定位


python代码:

element = self.driver.find_element_by_id("kw") 
element = self.driver.find_element(By.ID,"kw").send_keys("test")

NAME定位

python代码:

element = self.driver.find_element_by_name("wd")

Link Text定位

python代码:

element = self.driver.find_element_by_link_text("学术")

Partial Link Text定位

使用部分文本来定位

直接使用“123”来定位:

python代码:

element = self.driver.find_element_by_partial_link_text(**"123"**)

Xpath定位

XPath 使用路径表达式来选取 XML 文档中的节点或节点集。具体语法参考:https://www.w3school.com.cn/xpath/xpath_syntax.asp

比如我们定位“资讯”:

可以在console中输入JS代码:$x('//*[@id="s_tab"]//a[1]')

这样就可以找到资讯对应的元素:

python代码:

element = self.driver.find_element_by_xpath('//*[@id="s_tab"]//a[1]')

CSS Selector定位

CSS选择器是一种字符串模式,基于HTML标签,id,类和属性的组合来标识元素。

具体语法参见:https://www.runoob.com/cssref/css-selectors.html

我们依然定位“资讯”:

在console中输入:$('#s_tab a:nth-child(2)')

python代码:

element = self.driver.find_element_by_css_selector("#s_tab a:nth-child(2)")

完整测试代码

#!/usr/bin/python3
# -*-coding:utf-8-*-

from time import sleep
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

class TestLocator():
    def setup(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(5)
        # self.driver.maximize_window()

    def teardown(self):
        self.driver.quit()

    def test_id(self):
        self.driver.get("https://www.baidu.com/")
        element = self.driver.find_element_by_id("kw")
        element.send_keys("test")
        # self.driver.find_element(By.ID,"kw").send_keys("test")
        assert element.get_attribute("value") == "test"

    def test_name(self):
        element = self.driver.find_element_by_name("wd")
        element.send_keys("test")
        assert element.get_attribute("value") == "test"

    def test_linktext(self):
        self.driver.get("https://www.baidu.com/")
        element = self.driver.find_element_by_link_text("学术")
        element.click()
        sleep(5)

    def test_partial_link_text(self):
        self.driver.get("https://www.baidu.com/")
        element = self.driver.find_element_by_partial_link_text("123")
        element.click()
        sleep(5)

    def test_xpath(self):
        self.driver.get("https://www.baidu.com/")
        self.driver.find_element_by_id("kw").send_keys("test")
        sleep(2)
        self.driver.find_element_by_id("su").click()
        sleep(2)
        element = self.driver.find_element_by_xpath('//*[@id="s_tab"]//a[1]')
        element.click()
        sleep(10)

    def test_css(self):
        self.driver.get("https://www.baidu.com/")
        self.driver.find_element_by_id("kw").send_keys("test")
        sleep(2)
        self.driver.find_element_by_id("su").click()
        sleep(2)
        element = self.driver.find_element_by_css_selector("#s_tab a:nth-child(2)")
        element.click()

if __name__ == '__main__':
    pytest.main()

总结

在工作中比较常用的是ID和NAME定位,用起来比较方便。但很多情况下没有ID或者ID是动态变化的(比如使用Extjs生成的web页面),需要用到CSS Selector和Xpath来定位。

Xpath是一种XML路径语言,定位时采用遍历页面的方式,基本上能定位到所有web元素。CSS Selector 是一种样式表语言,查找 HTML DOM 中的元素。理论上CSS Selector比Xpath效率更高,个人感觉没有显著差异。其它差异还包括:

  1. Xpath可以通过文本来定位,而CSS Selector不能。
  2. Xpath可以通过子节点来定位父节点,CSS Selector是前向的,不能利用子节点定位父节点。
  3. CSS Selector语法相比Xpath更加简洁
--THE END--

系列文章

1、Selenium Webdriver 架构
2、Selenium Web元素定位方法
3、Selenium Web元素操作
4、Web自动化测试:xpath & CSS Selector定位
5、Selenium ActionChains、TouchAction方法
6、Selenium switch_to方法
7、Selenium Select下拉框
8、Selenium多浏览器测试
9、Selenium执行JavaScript脚本
10、selenium/appium 等待方式介绍
11、Selenium Grid:在多个主机上并行执行自动化脚本


欢迎关注公众号:「测试开发小记」及时接收最新技术文章!

### Selenium 中处理弹窗元素定位方法 #### 处理不同类型的弹窗 在使用 Selenium 进行 Web 自动化测试时,遇到多种类型的弹窗。每种弹窗有不同的处理方式。 对于 `iframe` 类型的弹窗,在尝试访问其内部元素之前,必须先切换到该框架: ```python chrome_driver.switch_to.frame(chrome_driver.find_element(By.ID, "frame_id")) # 切换至指定ID的iframe[^1] ``` 完成操作后记得返回默认内容以便继续后续的操作: ```python chrome_driver.switch_to.default_content() ``` 针对 HTML 页面中的简单对话框(alert),可以直接通过 WebDriver 提供的方法来接受或取消警告框: ```python # 接受警告框 driver.switch_to.alert.accept() # 取消警告框 driver.switch_to.alert.dismiss() ``` 当面对复杂的 JavaScript 对话框或其他形式的模态窗口时,则可能需要更灵活的方式来进行元素定位。例如,可以通过 XPath 表达式结合属性匹配来精确定位特定输入字段: ```python element = driver.find_element(By.XPATH, "//input[starts-with(@type,'text')]") ``` 有时也会碰到由 CSS 或者 JavaScript 动态生成的内容,这时就需要引入显式的等待机制以确保目标元素确实存在于 DOM 结构之中并可交互: ```python from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, timeout=10) element = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn-exit'))) element.click() # 假设点击退出按钮[^5] ``` 如果遇到了难以捉摸的问题——比如虽然能够成功查找到某个控件却始终无法对其执行任何动作——这可能是由于存在多个相同名称的选择器或者是异步加载的原因造成的。此时应该考虑增加适当的时间延迟或是调整选择策略,甚至重新评估整个流程设计是否合理[^3]。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值