我在我抓取的这个网站上每周会出现几次通知。我无法绕过它。
我可以运行代码。
el = driver.find_element_by_xpath("//input[@id='btnRead']")
driver.execute_script("arguments[0].click();", el)
这会清除它,但如果我将其留在代码中,则会出现 no such element 异常。如果我尝试像这样将其包装在 try/catch 中,则会发生事件。
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()
如果存在的话,这也会清除它,但如果不存在,则会出错。 我认为我做错了什么,但我尝试了几个不同的版本,但我总是收到错误,导致窗口挂起并停止脚本其余部分的执行。
任何想法都会很棒。
最佳答案
如果您想继续编写脚本,可以检查元素的长度。
如果元素的长度大于 0,则会点击。
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")
<小时/>
或者引入WebDriverWait
()和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")
您需要导入以下库。
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
关于Python Selenium 一个隐藏框架,有时会与 java 脚本断言一起出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59564151/