memo747
memo747

Reputation: 77

How to handle errors (unable to locate element) in Selenium

I am writting bot using Selenium for a game where is a lot of clicking. Sometimes it shows error Unable to locate element:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div/div[1]/header/div/div[1]/a

I have correct Xpath but sometimes it gives me an error in different parts in my code. It is not that I have one mistake and it always show error in one place. My problem is that those errors are random. I am handling it like this:

try:
    secondPhoto = self.driver.find_element_by_xpath(
                    '/html/body/span/section/main/article/div[2]/div/div[1]/div[1]')
    secondPhotoOpen = ActionChains(self.driver)
    secondPhotoOpen.move_to_element(secondPhoto)
    secondPhotoOpen.click()
    secondPhotoOpen.perform()
except:
    time.sleep(3)
    self.driver.find_element_by_xpath(
                    '/html/body/span/section/main/article/div[1]/div/div/div[1]/div[2]').click()

This is not a ideal solution. It still shows errors but less frequently. I am also using time.sleep. Usually errors show up when I am doing something else on internet or I have lags(this is the reason why I am using time.sleep) Now, I have about 50 .click() in my code and for all clicks I am doing try except but still it is not working correctly.

  1. Do you have an effective solution for this? How to write a code that use .click() to be 100% sure it works regardless lags, other browser activity?

  2. How to wait for full load of next page/image after click() ( I am using time.sleep)?

Upvotes: 1

Views: 655

Answers (1)

Andrei
Andrei

Reputation: 5647

You can use WebDriverWait:

btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "element_id")))
btn.click()

this will wait at least 10 seconds, until element will be clickable and only then clicks on it. Also I would recommend to read this. With WebDriverWait you don't have to have hard coded pauses.

Upvotes: 1

Related Questions