我需要获得xpath表达式。定位器已经使用@FindBy声明了,但是在测试用例执行期间,这是必需的,不管这里使用了任何定位器。
下面的表达式,例如,一旦找到元素,就需要存储在数据库中,以便在完成新的测试执行时,它与一个条目(在db表中)匹配。(必填)
//*[@role='img' and contains(text(),'search')]
以下是代码:
@FindBy(xpath = "//*[@role='img' and contains(text(),'search')]") public WebElement searchPopup;
@FindBy(xpath = "//*[@data-test='userMenu']") public WebElement userMenu;
public waitForElementVisible {
waitForLocatorVisibility(searchPopup);
System.out.println(searchPopup);
}
public static WebElement waitForLocatorVisibility(WebElement element) {
// standard webDriverWait method from selenium
return new WebDriverWait(driver, Duration.ofSeconds(45, 1)).until(ExpectedConditions.visibilityOf(element));
}
如果我打印返回的元素或直接打印它,它会在控制台中显示如下所示:
元素是:[FirefoxDriver: WINDOWS上的火狐(1679120c-e1f7-4422-8222-93f31208f037) -> xpath: //*->=‘img’并包含(文本(),'search')]
而在不同浏览器(如Chrome )上执行测试时,唯一的键会发生变化。它在日志中显示了Chrome而不是firefox。
有什么方法可以在这里获取/打印实际的XPath表达式,例如:
//*[@role='img' and contains(text(),'search')]
发布于 2022-08-27 04:31:14
可以使用下面的代码从WebElement中提取定位器。由于您使用的是PageFactory,所以在调用此方法之前,需要确保元素在DOM上找到,因为PageFactory将使用代理将这些字段初始化,并且在DOM中找到之前它们不包含您的webelement,所以一旦您执行诸如click或gettext之类的操作,查找就会发生。
private String getLocatorFromElement(WebElement element) {
By by = null;
String[] pathVariables = (element.toString().split("->")[1].replaceFirst("(?s)(.*)\\]",
"$1" + "")).split(":");
String selector = pathVariables[0].trim();
String value = pathVariables[1].trim();
switch (selector) {
case "id":
by = By.id(value);
break;
case "className":
by = By.className(value);
break;
case "tagName":
by = By.tagName(value);
break;
case "xpath":
by = By.xpath(value);
break;
case "cssSelector":
by = By.cssSelector(value);
break;
case "linkText":
by = By.linkText(value);
break;
case "name":
by = By.name(value);
break;
case "partialLinkText":
by = By.partialLinkText(value);
break;
default:
throw new IllegalStateException("locator : " + selector + " not found!!!");
}
return by.toString().split(":")[1];
}
与下面的示例一样,在从Webelement检索定位器值之前,我正在执行gettext操作。
PageFactory.initElements(drover, obj);
drover.get("https://www.google.com/");
obj.userMenu.getText();
String by = obj.getLocatorFromElement(obj.userMenu);
System.out.println(by);
https://stackoverflow.com/questions/73363706
复制