You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Selenium Java中通过CSS定位器基于标签文本获取元素值

使用Page Factory结合CSS定位器基于文本获取字段值

实现思路

  • 完全不依赖动态class,通过标签的文本内容定位目标字段容器
  • 优先采用CSS选择器,利用兄弟选择器和:has()伪类精准定位取值元素
  • 用Page Factory模式封装元素,实现页面元素与业务逻辑分离

Java代码实现(Selenium Page Factory)

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class UserProfilePage {
    // 定位UserName对应的取值元素:找到包含"UserName."文本的b标签所在列,再取相邻右侧列
    @FindBy(css = "div.ant-col-10:has(b:contains('UserName.')) + div.ant-col-14")
    private WebElement userNameElement;

    // 定位UserType对应的取值元素
    @FindBy(css = "div.ant-col-10:has(b:contains('UserType.')) + div.ant-col-14")
    private WebElement userTypeElement;

    public UserProfilePage(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }

    // 获取UserName文本值,去除首尾空格
    public String getUserName() {
        return userNameElement.getText().trim();
    }

    // 获取UserType文本值,去除首尾空格
    public String getUserType() {
        return userTypeElement.getText().trim();
    }
}

关键说明

  • CSS选择器逻辑:div.ant-col-10:has(b:contains('UserName.'))定位到包含目标文本标签的左侧列,+ div.ant-col-14选择其紧邻的右侧取值列,精准匹配页面结构
  • 兼容性提示::has()伪类需要Chrome 101+、Firefox 121+或其他支持CSS Selectors Level 4的浏览器版本;若需兼容旧版本,可改用以下XPath定位作为备选:
    @FindBy(xpath = "//div[contains(@class, 'ant-col-10') and .//b[text()='UserName.']]/following-sibling::div[contains(@class, 'ant-col-14')]")
    private WebElement userNameElement;
    
  • 使用方式:在测试代码中实例化UserProfilePage后,直接调用getUserName()和getUserType()即可获取对应字段值

内容的提问来源于stack exchange,提问作者Automater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 15:25:55