Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Problem: Having a bit of trouble figuring out how to implement the WebDriverWait method in Python Selenium.

I want to do nothing on NoSuchElementExceptions but use WebDriverWait on StaleElementReference, ElementNotInteractable, ElementClickIntercepted, and whatever ever new one pops up.

The below has worked for me on just StaleElementReference but what do I do If I want to incorporate all similar exceptions besides NoSuchElement? I beleive there's more than just this 3 that could pop up.

def click(selector):
    try:
        elem = browser.find_element_by_css_selector(selector)
        elem.click()      
    except NoSuchElementException:
        pass
    except StaleElementReferenceException:
        elem = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
        elem.click()

EDIT: Added Error Message from Solution from @BapRx

    elem.click()
    self._execute(Command.CLICK_ELEMENT)
    return self._parent.execute(command, params)
    self.error_handler.check_response(response)
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <span>...</span> is not clickable at point (730, 523). Other element would receive the click: <div id="JDCol" class="noPad">...</div>
  (Session info: chrome=87.0.4280.88)


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
    click(company_tab_selector) #Company Tab
    elem.click()
    self._execute(Command.CLICK_ELEMENT)
    return self._parent.execute(command, params)
    self.error_handler.check_response(response)
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <span>...</span> is not clickable at point (730, 523). Other element would receive the click: <div id="JDCol" class="noPad">...</div>
  (Session info: chrome=87.0.4280.88)'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
445 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could do this:

try:
    elem = browser.find_element_by_css_selector(selector)
    elem.click()      
except NoSuchElementException:
    pass
except Exception as e:
    print(e) # You can still log the error
    elem = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
    elem.click()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...