Python 和 Selenium:在 iframe 中定位并单击 cookie 按钮

Python and Selenium: Locating and clicking a button for cookies within an iframe

任何人都有解决方案,可以在带有重叠弹出窗口的网页中找到按钮 window,如下例所示:

from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'./geckodriver')
driver.get("https://www.academics.de/")
#after waiting for a while the popup window comes up
driver.find_elements_by_xpath("//*[contains(text(), 'Zustimmen')]")

返回的列表为空。 运行以下

driver.find_element_by_css_selector(".button-accept")

结果:

NoSuchElementException: Message: Unable to locate element: .button-accept

文本为电子邮件登录的元素在内,因此您必须:

  • 诱导 WebDriverWait 所需的 帧可用并切换到它.

  • 诱导 所需的 元素可点击.

  • 您可以使用以下任一项:

    • 使用CSS_SELECTOR:

      driver.get("https://www.academics.de/")
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='SP Consent Message']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[title='Zustimmen']"))).click()
      
    • 使用XPATH:

      driver.get("https://www.academics.de/")
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='SP Consent Message']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@title='Zustimmen']"))).click()
      
  • 注意:您必须添加以下导入:

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

参考

您可以在以下位置找到一些相关讨论:

  • Switch to an iframe through Selenium and python

您的问题的一个简单解决方法是使用 uBlock Origin extension + Fanboy's Annoyances blocklist on your Selenium instance so that these annoying cookies messages would outright never appear. A way of enabling extensions is described in this Whosebug answer:

  1. Create a new firefox profile via right click windows start button > run > firefox.exe -P
  2. Then add whatever extensions you want, ublock, adblock plus etc
  3. Call your profile folder with

profile = selenium.webdriver.FirefoxProfile("C:/test")

browser = selenium.webdriver.Firefox(firefox_profile=profile, options=ops)