![](/img/trans.png)
[英]Retrieving the value from a Selenium Webdriver WebElement field and passing it to a java variable
[英]Passing variable to webelement defined with annotation in Selenium Java
我使用注釋在 selenium java 中聲明 webelement。 在大多數情況下,我有簡單的定位器:
@FindBy(how = How.ID, using="login")
WebElement btnLogin;
public void clickLogin() {
btnLogin.click()
}
但是有時我需要將變量傳遞給 xpath 或任何其他定位器。 在這種情況下,我這樣做之前沒有聲明 webelement,而是在函數中:
public void clickElement(String elementName) {
driver.findElementByXpath("//android.widget.TextView[@text='" + elementName + "']")
}
我不喜歡它,因為定位器應該在一個地方之前被調用,而不是與代碼可見性的函數混合
我想過做這樣的事情:
String elementXpathPrePart= "//android.widget.TextView[@text='";
String elementXpathPostPart = "']";
進而
public void clickElement(String elementName) {
driver.findElementByXpath(elementXpathPrePart + elementName + elementXpathPostPart )
}
你有什么解決辦法嗎?
嗯,當您使用頁面工廠時,這是 Page 對象模型中的一個常見問題。 對此的解決方案:
使用常量,java 文件並保留所有的 xpaths 從那里引用
public class Constants{ public static final String myxpath="//input[@id='username'] } In-Page class:
@FindBy(how = How.ID, using=Constants.myxpath) WebElement btnLogin;
或者
在代碼中
public void clickElement(String elementName) {
driver.findElementByXpath(By. xpath(Constants.myxpath ).click()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.