We need to take into account that a web element, for instance a button, can dynamically go out of view depending on the screen resolution we test with. So how do we wait for an element that we want to click on and if we cannot find it, scroll to it and try again? We’ll use two methods that work for any web element.
- A
scrollToElement
method that gets the web element into view. - A
waitAndClick
method that uses thescrollToElement
method.
To make things more realistic we include waiting for a loading indicator to disappear before checking whether we can click on an element. The assumption is that the class containing our methods has an instance of WebDriver
called driver
.
We’ll use the JavascriptExecutor
in scrollToElement
.
private void scrollToElement(WebElement el) { if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor) driver) .executeScript("arguments[0].scrollIntoView(true);", el); } }
Now we can finish the job in waitAndClick
.
public void waitAndClick(WebElement el) { try { WebDriverWait wait = new WebDriverWait(driver, 5, 200); wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("loader"))); wait.until(ExpectedConditions.elementToBeClickable(el)).click(); catch (WebDriverException wde) { scrollToElement(el); el.click(); } }
This method tries to click on the element. If it fails, it scrolls to the element and tries to click again. That’s it!
can u do this same way for selenium python webdriver
Yes, that would be like this:
driver.execute_script(“arguments[0].scrollIntoView(true);”, el)
Where el is the web element you want to scroll to.