是否可以将selenium / webdriver“By”对象转换为sting,例如:
By locator1 = By.xpath("//a[contains(text(),'" + button2press + "')]");
By locator2 = By.cssSelector("input[class='image'][checked='checked']");
我需要这样的东西:
String str1 = "//a[contains(text(),'" + button2press + "')]";
String str2 = "input[class='image'][checked='checked']";
如果我能找到定位“方法”,这将是一个奖励:
String method1 = "xpath";
String method2 = "cssSelector";
假设我们有2个选择器
By.cssSelector("input[class='here i am']");
By.xpath("//*[@class='here i am']");
为了将它们转换为String,请使用toString()
方法。输出如下:
By.cssSelector: input[class='here i am']
By.xpath: //*[@class='here i am']
以上是字符串。你有选择器。让我们找到定位方法。如您所见,定位方法已经在我们的String中。我们只需要解析它以获得定位方法。我们可以通过多种方式做到这一点。 Regex
或split()
或indexOf()
例:
String mySelector = "By.cssSelector: input[class='here i am']";
String locating method = mySelector.split(":")[0].trim()
现在,我们可以创建方法来获得所需的结果。
public String getSelector(By by) {
return by.toString().split(":")[1];
}
public String getLocatingMethod(By by) {
return by.toString().split(":")[0]; //returns "By.cssSelector", "By.xpath" etc
}
以下代码应该有效:
By locator1 = By.xpath("//a[contains(text(),'" + button2press + "')]");
String str = locator1.toString();
String pat1 = "(By.)(.*)(:)( )(.*)";
Pattern pattern = Pattern.compile(pat1);
Matcher matcher = pattern.matcher(str);
if(matcher.find()) {
System.out.println(matcher.group(2));
System.out.println(matcher.group(5));
}
在功能上,使用经过验证且功能强大的toString() Java方法,您可以将selenium / webdriver By对象转换为String。但是很多都取决于你正在处理的用例。
在这一点上值得一提的是,WebDriver方法findElement()
和findElements()
只接受By
类型的参数如下:
WebElement findElement(By by)
Parameters:
by - The locating mechanism
Returns:
The first matching element on the current page
Throws:
NoSuchElementException - If no matching elements are found
java.util.List<WebElement> findElements(By by)
Parameters:
by - The locating mechanism to use
Returns:
A list of all WebElements, or an empty list if nothing matches
因此,即使您将selenium / webdriver By对象转换为String对象,它们也无法在@Tests中使用。因此,将By对象强制转换为String对象将不会添加任何值。
但是,如果要传递String以构造将用于构造By对象的唯一动态xpath
,则可以始终按如下方式编写函数,以使用可变文本调用特定click()
标记上的<a>
,如下所示:
public void clickElement(string myElement)
{
driver.FindElement(By.xpath("//a[.='" + myElement + "']")).click();
}
现在,如果您的应用程序测试(AUT)中有多个要单击的链接,您可以随时从clickElement(string myElement)
或main()
注释类调用@Test
函数,如下所示:
clickElement("Login");
clickElement("Logout");