Home > Software engineering >  How to solve "Move target out of bounds" Selenium error?
How to solve "Move target out of bounds" Selenium error?

Time:01-05

I'm trying to simulate clikcin on the "Load more listings" button on the "https://empireflippers.com/marketplace/" webpage untill the button no longer is. I tried the following code but it results in "Move target out bounds" error.

from selenium import webdriver      
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.common.action_chains import ActionChains




HOME_PAGE_URL = "https://empireflippers.com/marketplace/"

driver = webdriver.Chrome('./chromedriver.exe')
driver.get(HOME_PAGE_URL)

while True:
    try:
        element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,"//button[contains(text(),'Load More Listings')]")))
        ActionChains(driver).move_to_element(element).click().perform()

    except Exception as e:
        print (e)
        break
print("Complete")
time.sleep(10)
page_source = driver.page_source

driver.quit()

I'm expecting to retrieve the html code of the full web page without load more listings button.

CodePudding user response:

So it seems that the button that you are trying to click is not visible on the screen. You could try this:

driver.execute_script("arguments[0].click();", driver.find_element(By.XPATH, "//button[contains(text(),'Load More Listings')]"))

To click the button.

CodePudding user response:

I have no idea why, but trying to click twice works for me. [I still get the same error if I try to click twice with ActionChains, and I'm not familiar enough with ActionChains to try to fix that; my usual approach is to use .execute_script to scroll to the element with JavaScript and then just apply .click() to the element, so that's what I've done below.]

while True:
    try:
        element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,"//button[contains(text(),'Load More Listings')]")))

        # ActionChains(driver).move_to_element(element).click().perform()
        driver.execute_script('arguments[0].scrollIntoView(false);', element)
        try: element.click() # for some reason, the 1st click always fails
        except: element.click() # but after the 1st attempt, the 2nd click works...

    except Exception as e:
        print (e)
        break
  • Related