页面工厂@FindBy

Page Factory @FindBy

我目前正在学习页面对象模型 (POM),我正在尝试使用 @FindBy 访问特定的 Web 元素,但我不确定如何将我的元素的语法正确写入 @FindBy?

我有的是:

driver.findElement(By.cssSelector("a[dta-qid='inventory']");

所以我的问题是如何将 a[da-qid='inventory'] 正确地放入 @FindBy?


a[da-qid='inventory'],我的意思是它选择每个 <a>da-qid 值以 'inventory'.

开头的元素

你为什么不通读 this? Use of @FindsBy is easier if you do that with How Enum。在这种情况下,您有多种选择。使用 cssSelector 它应该看起来像这样

@FindBy(how = How.css, using = "a[dta-qid='inventory']") 
WebElement foobar;

如果您假设使用此选择器会找到多个元素,请尝试以下操作:

@FindBy(css="a[da-qid='inventory']")
List<WebElement> elements;

只是不要忘记在 da-qid='inventory'dta-qid='inventory'

之间正确选择

您可以使用 XPath 选择器:

driver.findElement(By.xpath("//a[contains(@da-qid,'inventory')]");

@FindBy(xpath = "//a[contains(@da-qid,'inventory')]")
WebElement inventoryLink;

分别

@FindAll(xpath = "//a[contains(@da-qid,'inventory')]")
List<WebElement> inventoryLinks;

理论上 XPath "//a[startsWith(@da-qid,'inventory')]" 也存在,但它并不适用于我的所有 WebDriver。