webdriver,cast" By"串起来

时间:2018-02-28 08:42:04

标签: java selenium selenium-webdriver webdriver

是否可以施放硒/网络驱动器" By"反对刺痛,例如:

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";

3 个答案:

答案 0 :(得分:0)

假设我们有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中。我们只需要解析它以获得定位方法。我们可以通过多种方式做到这一点。 Regexsplit()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
}

答案 1 :(得分:0)

以下代码应该有效:

    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));
    }   

答案 2 :(得分:0)

从功能上讲,使用久经考验且功能强大的toString() Java 方法,您可以将selenium / webdriver 对象转换为字符串。但是很多都取决于你正在处理的 usecase

此时值得一提的是,WebDriver方法findElement()findElements()仅接受By类型的参数,如下所示:

  • findElement()

    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
    
  • findElements()

    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 对象投射到字符串对象,他们也无法在 @Tests 中使用。因此,将对象转换为字符串对象不会添加任何值。

但是,如果您想传递一个字符串来构建一个独特的动态xpath,它将用于构建一个 By 对象,那么您总是可以编写一个函数如下,使用变量文本调用特定click()标记上的<a>,如下所示:

public void clickElement(string myElement)
{
    driver.FindElement(By.xpath("//a[.='" + myElement + "']")).click();
}

现在,如果您的受测试应用程序(AUT)有多个要点击的链接,您可以随时从clickElement(string myElement)或{{1}调用main()功能注释类如下:

@Test