Java Selenium webdriver 显式等待

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20077860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:55:48  来源:igfitidea点击:

Selenium webdriver explicit wait

javaseleniumselenium-webdriver

提问by vslat

I'm writing some automated tests for using the selenium chrome driver. I trying to write a reusable method that will explicitly wait for elements to appear and then call this method in other classes. Seems pretty straight forward but its not doing what I want it do. Here is the method that I have.

我正在编写一些使用 selenium chrome 驱动程序的自动化测试。我试图编写一个可重用的方法,该方法将显式等待元素出现,然后在其他类中调用此方法。看起来很简单,但它没有做我想要它做的事情。这是我拥有的方法。

public String waitForElement(String item) {
    WebDriverWait wait = new WebDriverWait(driver,30);
    WebElement element = wait.until(
                        ExpectedConditions.elementToBeClickable(By.id(item)));
    return item;
}

Then I call the method and pass it a parameter like this:

然后我调用该方法并向它传递一个参数,如下所示:

waitForElement("new-message-button");

That doesn't seem to become working, can someone give some insight?

这似乎不起作用,有人可以提供一些见解吗?

回答by drunkel

I built a package using Selenium and waiting was one of the biggest issues I had. In the end, the methods as you described above wouldn't work. I had to resort to doing a simple implicit wait for any dynamic elements, as described below

我使用 Selenium 构建了一个包,等待是我遇到的最大问题之一。最后,你上面描述的方法不起作用。我不得不对任何动态元素进行简单的隐式等待,如下所述

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

隐式等待是告诉 WebDriver 在尝试查找一个或多个元素(如果它们不是立即可用)时轮询 DOM 一段时间。默认设置为 0。设置后,将在 WebDriver 对象实例的生命周期内设置隐式等待。

Code:

代码:

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));

src

源文件

Hope that helps.

希望有帮助。

回答by drunkel

I wrote an explicit wait for my selenium test in the following manner:

我以下列方式为我的 selenium 测试写了一个明确的等待:

I declared my WebElement to be found with an @FindBy annotation added referencing the Id as follows:

我声明我的 WebElement 可以找到,并添加了一个 @FindBy 注释,引用了 Id,如下所示:

@FindBy(how = How.ID, using = "home")
private WebElement home;

Then my method that waits for an element to load was written as follows:

然后我的等待元素加载的方法写成如下:

public WebElement isElementLoaded(WebElement elementToBeLoaded) {
    WebDriverWait wait = new WebDriverWait(driver, 15);
    WebElement element = wait.until(ExpectedConditions.visibilityOf(elementToBeLoaded));
    return element;
}

This allowed me to reference any element I was waiting for by name that I had annotated with a find by, regardless of the @FindBy method used.

这使我可以通过使用 find by 注释的名称引用我正在等待的任何元素,而不管使用的 @FindBy 方法如何。

回答by nazar_art

Your problem is that you passed String to method parameter:

您的问题是您将 String 传递给方法参数:

public String waitForElement(String item) {

公共字符串waitForElement(字符串项目){

You have to pass your WebElement, something like:

您必须传递您的 WebElement,例如:

public boolean visibilityOfElementWait(WebElement webElement) {
    if (webElement != null) {
        try {
            WebDriverWait wait = new WebDriverWait(Driver.getCurrentDriver(), 20);
            wait.until(ExpectedConditions.visibilityOf(wrappedElement));
            highlightElement(webElement);
            return true;
        } catch (Exception e) {
            return false;
        }
    } else
        Logger.logError("PageElement " + webElement.getText() + " not exist");
    return false;
}

public void highlightElement(WebElement element) {
    if (!Config.getProperty(Config.BROWSER).equalsIgnoreCase("ANDROIDHYBRID")) {

        String bg = element.getCssValue("backgroundColor");

        for (int i = 0; i < 4; i++) {
            Driver.getDefault()
                    .executeScript("arguments[0].style.backgroundColor = 'red'", element);
            Driver.getDefault()
                    .executeScript("arguments[0].style.backgroundColor = '" + bg + "'", element);
        }

   //            String highlightElementScript = "arguments[0].style.backgroundColor = 'red';";
   //            Driver.getDefault().executeScript(highlightElementScript, element);
    }
}

回答by Surya

We can develop implicit wait on our own.

我们可以自己开发隐式等待。

Use this code; it should also work the same as implicit wait.

使用此代码;它也应该与隐式等待相同。

//=== Start of Implicit Wait Statement ===

public void implicit_Wait_ID(String str) throws Exception{

        for(int i=0;i<60;i++){
            try{
                driver.findElement(By.id(str)).isDisplayed();
                break;
            }catch(Exception e){Thread.sleep(2000);

            }   
        }
}
//=== End of Implicit Wait Statement ===    

Use this method by passing the ID value:

通过传递 ID 值使用此方法:

public void loginGmail() throws Exception
{
        driver.findElement(By.id("Email")).sendKeys("Mail ID");
        driver.findElement(By.id("next")).click();
        implicit_Wait_ID("Passwd");
        driver.findElement(By.id("Passwd")).sendKeys("Pwd value");
        driver.findElement(By.id("signIn")).click();
}

If it is Xpath, LinkText, just create one of the above methods for all locator types and reuse it nnumber of times in your script.

如果是 Xpath、LinkText,只需为所有定位器类型创建上述方法之一,并n在脚本中重复使用它多次。

回答by anuja jain

You can use Explicit wait or Fluent Wait

您可以使用显式等待或流畅等待

Example of Explicit Wait -

显式等待示例 -

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));

Example of Fluent Wait -

Fluent 等待示例 -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
.withTimeout(20, TimeUnit.SECONDS)          
.pollingEvery(5, TimeUnit.SECONDS)          
.ignoring(NoSuchElementException.class);    

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));     
 }  
});

Check this TUTORIALfor more details.

查看此教程以获取更多详细信息。

回答by virender rana

Just use this method.I hope it will work perfectly.

就用这个方法吧,希望能完美运行。

public void waitForElement(String item) {
    WebDriverWait wait = new WebDriverWait(driver,30);
    WebElement element =  wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("item")));
}

Then call the method :

然后调用方法:

waitForElement("new-message-button");

回答by prasadraj d

public static void clickOn(WebDriver driver, WebElement locator, int timeout)
 {
        new WebDriverWait(driver,timeout).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(locator));
        locator.click();

    }

Call the above method in the main method then we will get explicitly wait functionality.

在 main 方法中调用上述方法,然后我们将获得显式等待功能。