Python Selenium 无法点击关闭按钮

Python Selenium cannot click the close button

我正在尝试从 https://projects.propublica.org/nonprofits 下载数据用于我的研究。打开页面时,会弹出一条通知 window。我尝试使用 python selenium 来关闭它。我的代码如下,

from selenium.webdriver import Chrome
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = Chrome()

driver.get('https://projects.propublica.org/nonprofits')
driver.find_element(By.XPATH, "/html/body/div[1]/div/div[2]/p[2]/a").click()

我收到错误消息:selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法定位元素:{"method":"xpath","selector":"/html/body/div[1] /div/div[2]/p[2]/a"} (会话信息:chrome=99.0.4844.51)

我将代码修改为

driver.get('https://projects.propublica.org/nonprofits')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[1]/div/div[2]/button"))).click()

错误信息是TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException:消息: 堆栈跟踪: 回溯: 序号 0 [0x005E9943+2595139] ...

非常感谢任何超越通知的建议 windows。谢谢。

  1. 您尝试单击的元素在 iframe 内 - 您必须先切换到该 iframe 才能访问该元素
  2. 您必须添加等待以让元素在访问之前加载。
    这样效果会更好:
from selenium.webdriver import Chrome
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = Chrome()

driver.get('https://projects.propublica.org/nonprofits')
wait = WebDriverWait(driver, 20)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.syndicated-modal")))
wait.until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@href,'newsletter-roadblock')]"))).click()

在 iframe 中完成工作后,您需要使用

切换到默认内容
driver.switch_to.default_content()