我正在寻找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)));
}因此,Xpath....而不是每次都调用By.CssSelector。我想让它从我调用的任何地方获取参数...我在python中做到了,但由于某种原因,在Java中我无法做到这一点。
发布于 2014-11-15 06:52:17
你不需要使用string来实现这一点:
public WebElement waitforElement(By locator)
{
WebDriverWait wait = new WebDriverWait(driver,10);
return wait.until(ExpectedConditions.elementToBeClickable(locator));
} By已经是定位机制的抽象。您不需要通过使用string来使它们更加通用,使用上面的方法如下所示:
waitForElement(By.cssSelector("something"));
waitForElement(By.id("something"));
waitForElement(By.xpath("something"));而不是:
waitForElement("xpath", "something");
waitForElement("id", "something");
waitForElement("css", "something");好多了,不是吗?例如,如果我拼错了"xpath",您就不太可能遇到手动错误。还使用内置的框架类,因此您不会重复工作。
发布于 2014-11-15 06:57:31
通过一些思考,您可以尝试如下所示:
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的子类。
我还没试过,但应该可以用。
发布于 2014-11-17 04:44:02
为什么不使用简单的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;
}https://stackoverflow.com/questions/26939821
复制相似问题