I am unable to click a button that's outside of the viewport on a page. I have tried a couple of things, none of which work:
button.click()
Actions.click(button).peform()
Actions.moveToElement(button).click().build().peform()
All of the above throw a MoveTargetOutOfBoundsException
.
I have tried scrolling the button into view, but these all don't do anything:
((JavascriptExecutor)driver).executeScript("window.scrollTo(0, document.body.scrollHeight)")
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", button)
driver.findElement(By.tagName("body")).sendKeys(Keys.PAGE_DOWN)
I have checked the page for iframe
s; the page doesn't contain any. It should be noted that when I add a delay and scroll the page down manually, the button is immediately clicked when it's in view, so that leads me to believe it's not an issue with the button, but rather with the page not wanting to be scrolled down.
I cannot share the page, but I can provide snippets of the page's HTML if needed.
- Java 16
- Selenium 4
- Chromedriver 99
CodePudding user response:
You can try scrolling the page with method independent to that element, like
((JavascriptExecutor)driver).executeScript("window.scrollTo(0, document.body.scrollHeight)")
Checking each time for presence or visibility of that button
element.
And only when this condition is met to click on that element with Selenium button.click()
method or with Actions Actions.moveToElement(button).click().build().peform()
CodePudding user response:
You need to take care of a couple of things as follows:
button.click()
: Ideally to invoke click on the element you need to induce WebDriverWait for the elementToBeClickable() which automatically scrolls the element within the viewport.new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("elementCssSelector"))).click();
Actions.click(button).peform()
: Same as the previous step you may like to induce WebDriverWait for theelementToBeClickable()
and build and peform as follows:Actions.click(new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("elementCssSelector")))).build().peform()
Actions.moveToElement(button).click().build().peform()
: To move the focus to the element you need to induce WebDriverWait for the visibilityOfElementLocated() as follows:Actions.moveToElement(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("elementCssSelector")))).click().build().peform()