简体   繁体   English

使用Java中的字符串动态生成硒查询

[英]Generate selenium query dynamically using a string in Java

I was trying to generate a selenium query dynamically as follows but it did not work: 我试图按如下方式动态生成硒查询,但是它不起作用:

String Query = "By."+Selector+"("+Expression+")))";

element = wait.until(ExpectedConditions.elementToBeClickable(Query));

How to achieve this requirement please? 请问如何达到这个要求?

According to the documentation and the error you are getting, there does not seem to exist an elementToBeClickable method which takes a string as parameter. 根据文档和您遇到的错误,似乎不存在使用字符串作为参数的elementToBeClickable方法。

Checking the By documentation however, which seems to be one of the input parameters which the method you are after takes, one can see that they can construct it from a string. 但是,检查By文档,这似乎是您要使用的方法所采用的输入参数之一,您可以看到他们可以从字符串构造它。

In short, your code would need to change to something like so: 简而言之,您的代码将需要更改为以下内容:

String cssQuery = ... //You can construct the CSS query dynamically.
element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(cssQuery)));

Looks like you want to get an element By query, using selector and expression parameters and then pass result to ExpectedConditions. 看起来您想使用选择器表达式参数通过查询获取元素,然后将结果传递给ExpectedConditions。 So may be you need universal method for this? 那么您可能需要通用方法吗?

Like: 喜欢:

public By getSeleniumQuery(String selector, String expression){
    if(selector.equalsIgnoreCase("id")){
        return By.id(expression);
    }
    else if(selector.equalsIgnoreCase("name")){
        return By.name(expression);
    }
    else if(selector.equalsIgnoreCase("class")){
        return By.className(expression);
    }
    else if(selector.equalsIgnoreCase("css")){
        return By.cssSelector(expression);
    }
    else if(selector.equalsIgnoreCase("link")){
        return By.linkText(expression);
    }
    else if(selector.equalsIgnoreCase("partialLink")){
        return By.partialLinkText(expression);
    }
    else if(selector.equalsIgnoreCase("tag")){
        return By.tagName(expression);
    }
    else if(selector.equalsIgnoreCase("xpath")){
        return By.xpath(expression);
    }
    else{
        throw new IllegalArgumentException("Unknown selector - " + selector);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM