IF / THEN Statement in Selenium

Viewed 110

I run this code

#Gets to the Calendar for the week with the Login Details

calendar = driver.get('https://www.investing.com/economic-calendar/')

time.sleep(5)

driver.find_element_by_xpath('/html/body/div[9]/div[3]')

driver.find_element_by_xpath('//*[@id="onetrust-accept-btn-handler"]').click()

time.sleep(5)

driver.find_element_by_xpath('/html/body/div[10]/div')

driver.find_element_by_xpath('/html/body/div[10]/div/div[4]/button[1]').click()

Sometimes I successful sometimes I get error

ElementClickInterceptedException: element click intercepted: Element <a onclick="overlay.overlayLogin();" href="javascript:void(0);" class="login bold">...</a> is not clickable at point (821, 19). Other element would receive the click: <div class="allow-notifications-popup-wrapper shown">...</div>
  (Session info: chrome=84.0.4147.135)

Because a naughty pop-up/alert doesn't always appear.

How can I write a IF (pop up is there) THEN click it

OR

IF pop-not there skip the following two lines?

Thanks

3 Answers
WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);

Should be able to bypass the pop-up entirely.

there might be a lot of ways to solve youre problem, but since you are basically trying to avoid a situation leading to this exact error, i think it will be the simplest to use a TRY/EXCEPT:

try:
    driver.find_element_by_xpath('/html/body/div[10]/div/div[4]/button[1]').click()
except ElementClickInterceptedException:
    pass

does it solve your problem?

JavaScript click will work however it bypassed the actual reason which may be a potential bug.

ElementClickInterceptedException: element click intercepted:

This Exception can occur due to multiple reasons. As per selenium docs reason for above exception is:

Indicates that a click could not be properly executed because the target element was obscured in some way.

To resolve this issue you can use webdriverwait and then check if element is clickable and then click on it

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "YOURXPATH']"))).click()

Refer https://selenium-python.readthedocs.io/waits.html

Related