I have a notification that appears in a couple of times a week on this website I scrape. And I can't get around it.
I can run the code.
el = driver.find_element_by_xpath("//input[@id='btnRead']")
driver.execute_script("arguments[0].click();", el)
Which clears it, but if I leave it in my code it gives me a no such element exception. Event if I try to wrap it in try/catch like so.
from selenium.common.exceptions import NoSuchElementException
try:
el = driver.find_element_by_xpath("//input[@id='btnRead']")
driver.execute_script("arguments[0].click();", el)
except NoSuchElementException:
print(nonefound)
sleep(5)
driver.quit()
This also clears it, if it exists but if it doesn't, error. I assume I am doing something wrong but I have tried a few different versions of this and I always get the error which leaves the windows hanging and stops the execution of the rest of the script.
Any ideas would be great.
You can check the length of the element in case you want to continue your scripts.
If length of the elements more that 0 this will click.
if len(driver.find_elements_by_xpath("//input[@id='btnRead']"))>0 :
el = driver.find_element_by_xpath("//input[@id='btnRead']")
driver.execute_script("arguments[0].click();", el)
else:
print("nonefound")
Or induce WebDriverWait
() and visibility_of_element_located
()
try:
el = WebDriverWait(driver,5).until(EC.visibility_of_element_located(("//input[@id='btnRead']")))
driver.execute_script("arguments[0].click();", el)
except NoSuchElementException:
print("nonefound")
You need to import following libraries.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException