有没有办法,将变量与By连接起来。 for Selenium Webdriver在Java中

时间:2014-11-14 22:20:27

标签: java selenium selenium-webdriver

我正在寻找Java中的解决方案 - Selenium Webdriver ..我创建了一个函数

public WebElement waitforElementCss(String locator)
{
    WebDriverWait wait = new WebDriverWait(driver,10);

    return wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(locator)));
}

我想做的是,让它像这样动态

public WebElement waitforElementCss(String type, String locator)
{
    WebDriverWait wait = new WebDriverWait(driver,10);

    return wait.until(ExpectedConditions.elementToBeClickable(By.type(locator)));
}

所以不是每次都调用By.CssSelector,Xpath ....我想让它从我调用的时候得到参数...我曾经在python中做过但是出于某种原因在Java中我无法做到..

3 个答案:

答案 0 :(得分:3)

您不需要使用string来实现此目的:

public WebElement waitforElement(By locator)
{
    WebDriverWait wait = new WebDriverWait(driver,10);

    return wait.until(ExpectedConditions.elementToBeClickable(locator));
}   

By已经是定位机制的抽象。使用string' s,您不需要使用上述方法使它们更通用:

waitForElement(By.cssSelector("something"));
waitForElement(By.id("something"));
waitForElement(By.xpath("something"));

而不是:

waitForElement("xpath", "something");
waitForElement("id", "something");
waitForElement("css", "something");

更好,不是吗?如果我拼错了#34; xpath",你不太可能会出现手动错误。还使用内置框架类,因此您不能复制工作。

答案 1 :(得分:1)

通过一些反思你可以尝试类似的东西:

public static <E> WebElement waitForElement(Class<E> byClass, String locator) 
        throws Exception {
    WebDriverWait wait = new WebDriverWait(driver,10);
    By byObject = (By) byClass.getConstructor(String.class).newInstance(locator);
    return wait.until(ExpectedConditions.elementToBeClickable(byObject);
}

然后叫它:

WebElement cssElem = waitForElement(By.ByCssSelector.class, "something");
WebElement otherElem = waitForElement(By.ById.class, "someId");

作为第一个参数,您可以使用By的子类。

我还没试过,但它应该有用。

答案 2 :(得分:0)

为什么不使用简单的if else或switch?

public WebElement waitforElementCss(String type, String locator) {
    WebDriverWait wait = new WebDriverWait(driver,10);
    WebElement element = null;
    if (type.equals("id")) {
        wait.until(ExpectedConditions.elementToBeClickable(By.id(locator)));
    } else if (type.equals("name")) {
        wait.until(ExpectedConditions.elementToBeClickable(By.name(locator)));
    } else if (type.equals("css")) {
        wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(locator)));
    }
    return element;
}