Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium wait for an element

Tags:

java

selenium

I am trying to learn selenium, one of the issues I am having is waiting for elements, I'll explain it.

I am doing a java program to auto translate by using google translate. But due to the asynchronous nature of google translate there are no way to get the element without waiting for it, code crashes because it doesn't find the element, and the element doesn't exist at the time the code requires it, you must wait a little until the server respond your request.

I think it is not a estrange situation dealing with selenium and webpages so I think there must be an easy way to do it. By the moment this is the code I have created to manage the situation.

public void translation(String s) {

    System.setProperty("webdriver.chrome.driver", "C:\\Robots\\chromedriver.exe");

    WebElement webDriver = new ChromeDriver();

this is the code I think there should be a better way to do,

I have used a method to wait until the translation is ready

    waitForElement("//*[@id='result_box']");


    System.out.println("prhase: " + s + " tranlsation: " + response.getText());

    webDriver.close();
}

private void waitForElement(String element) {
    WebElement response;
    do {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        response = webDriver.findElement(By.xpath(element));

    } while (response.getText().isEmpty());
}

Can you say me how to do it easy please?

like image 413
David Marciel Avatar asked Mar 07 '26 12:03

David Marciel


1 Answers

You are using Thread.sleep which isn't actually waiting for the element, it's just waiting for 3 seconds regardless.

You could do something like this instead.

private void waitForElement(String element) {
 WebDriverWait wait = new WebDriverWait(Driver, 10); // Wait for 10 seconds.
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(element)));
 WebElement element = driver.findElement(By.xpath(element));

}

There is no need for the try / catch block either unless your expecting something weird to happen. The above code, will wait for the element to appear for 10 seconds. Not sure if you need to use the last line of code or not.

Hope it helps!

like image 193
Moser Avatar answered Mar 10 '26 02:03

Moser