Home > Software design >  Element could not be scrolled into view error while trying to click button with Selenium
Element could not be scrolled into view error while trying to click button with Selenium

Time:04-15

When i inspect the button I can see this:

<button type="button"  role="button" data-nav-close="" data-testid="application-header-login-link">Log in</button>

I have tried finding the element with these commands but it does not work:

driver.findElement(By.xpath("//button[contains(text(),'Log in')]")).click();
driver.findElement(By.xpath("//button[@type='button' and text()='Log in']")).click();

I get an error in console:

Element could not be scrolled into view

Any ideas on why this is happening? I even added a Thread.sleep(10000) before running these commands.

CodePudding user response:

I request you to please add more details. Based on my understanding & knowledge, I can suggest you to try these things:

I'm writing the code in Java based on the latest versions of all components. So, please refer to the documentation of your version in case.

Using JavascriptExecutor & Explicit Wait (kindly import the appropriate libraries first):

WebElement logInBtn = driver.findElement(By.xpath("//button[@type='button' and text()='Log in']");
/* Declaring wait to be able to use explicit wait */
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(seconds));
wait.until(ExpectedConditions.elementToBeClickable(logInBtn));
JavascriptExecutor jse = (JavascriptExecutor)driver;
/* Bringing element into view */
jse.executeScript("arguments[0].scrollIntoView(true);", logInBtn);
/* Click using javascript if click() method doesn't work */
jse.executeScript("arguments[0].click();", loginBtn);

/* driver is a variable for your WebDriver instance */

CodePudding user response:

There could be some other element overlapping the same position. This can happen if elements don't have a defined position (or have relative positions) and the resolution crunches the elements to overlap.

CodePudding user response:

To click on the <button> with text as Log in you need to induce WebDriverWait for the elementToBeClickable() which by default scrolls the element into the view and you can use either of the following locator strategies:

compatible code

  • cssSelector:

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.wds-c-button--primary.wds-c-button--small.wds-c-button.wds-u-hide--nav-width-down[data-testid='application-header-login-link']"))).click();
    
  • xpath:

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='wds-c-button--primary wds-c-button--small wds-c-button wds-u-hide--nav-width-down' and text()='Log in']"))).click();
    
  • Related