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

如何从对象仓库而非页面对象中直接获取Selector属性?

从对象仓库对象获取选择器值的可行方案

别再用GetProperty或GetAttribute了——这两个方法是用来获取页面元素运行时的实际属性,而不是对象仓库里预定义的选择器规则,返回null很正常。要直接提取对象仓库中存储的选择器,得根据你使用的测试工具来操作:

针对UFT(QTP)共享对象库

直接通过对象的Description属性访问预定义的选择器属性:

  • 获取XPath选择器:
    Dim xpathVal
    xpathVal = Browser("Browser").Page("Page").WebElement("WebElement").Description("xpath")
    
  • 获取ID选择器:
    Dim idVal
    idVal = Browser("Browser").Page("Page").WebButton("WebButton").Description("html id")
    

注意要和你在对象库中定义的属性名完全匹配(比如大小写、拼写)。

针对Selenium Page Factory(Java/C#)

通过反射获取FindBy/FindsBy注解里的选择器内容:

Java 示例

import org.openqa.selenium.support.FindBy;
import java.lang.reflect.Field;

// 你的Page类
public class LoginPage {
    @FindBy(xpath = "//input[@id='username']")
    private WebElement usernameInput;
}

// 提取选择器的代码
Field field = LoginPage.class.getDeclaredField("usernameInput");
FindBy findByAnno = field.getAnnotation(FindBy.class);
String xpathSelector = findByAnno.xpath(); // 拿到预定义的XPath

C# 示例

using OpenQA.Selenium.Support.PageObjects;
using System.Reflection;

public class LoginPage {
    [FindsBy(How = How.XPath, Using = "//input[@id='username']")]
    private IWebElement usernameInput;
}

// 提取选择器的代码
FieldInfo field = typeof(LoginPage).GetField("usernameInput", BindingFlags.NonPublic | BindingFlags.Instance);
FindsByAttribute attr = field.GetCustomAttribute<FindsByAttribute>();
string selector = attr.Using; // 拿到预定义的选择器值

针对自定义对象仓库(如JSON/XML配置)

如果是你自己实现的对象仓库(比如用JSON文件存储元素定位规则),直接读取配置文件中对应的字段即可,比如解析JSON后提取selector字段的值。

核心逻辑就是:区分页面元素的运行时属性和对象仓库的预定义选择器——前者用GetProperty/GetAttribute,后者要从对象仓库的存储结构(工具API、注解、配置文件)中直接读取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:10:13