如何使用 python 处理 selenium 中嵌套 iframe 中的 cookie 接受按钮?

How do I handle cookie accept button within nested iframes in selenium with python?

我几乎尝试了所有方法并在 SO 上进行了搜索,但无法通过 gmx.com 上的 cookie 接受。希望有人能帮忙。到目前为止我已经尝试过:

driver = webdriver.Chrome(CHROMEPATH)
driver.get('https://www.gmx.com')
time.sleep(5)
cookie_accept = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, '//button[@id="onetrust-accept-btn-handler"]')))
cookie_accept.click()

===AND===

driver = webdriver.Chrome(CHROMEPATH)
driver.get('https://www.gmx.com')
wait = WebDriverWait(driver, 15)
wait.until(EC.element_to_be_clickable(
    (By.CSS_SELECTOR, "div[style='onetrust-style'] button[id*='onetrust-accept-btn-handler']")))
driver.find_element_by_css_selector("div[style='onetrust-style'] button[id*='onetrust-accept-btn-handler']").click()
time.sleep(10)
driver.quit()

我做错了什么?!非常感谢任何帮助!!

元素 同意并继续 位于嵌套的 元素中,因此您必须:

  • 框架引入WebDriverWait并切换到它.

  • child 框架引入 可用并切换到它.

  • 诱导 所需的 元素可点击

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

    • 使用CSS_SELECTOR:

      driver.get("https://www.gmx.com/consentpage")
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.permission-core-iframe")))
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src^='https://plus.gmx.com/lt']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#onetrust-accept-btn-handler"))).click()
      
    • 使用 XPATH:

      driver.get("https://www.gmx.com/consentpage")
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='permission-core-iframe']")))
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@src, 'https://plus.gmx.com/lt')]")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='onetrust-accept-btn-handler']"))).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

此元素位于 iframe 内。 iframe 内的 iframe。因此,您必须切换到内部 iframe 才能访问该元素。
像这样:

driver.get("https://www.gmx.com/consentpage")  
wait = WebDriverWait(driver, 20)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.permission-core-iframe")))  
wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@src,'plus')]")))
wait.until(EC.visibility_of_element_located((By.XPATH, '//button[@id="onetrust-accept-btn-handler"]'))).click()