Python Selenium:无法找到 xpath 以单击 iframe 中的元素

Python Selenium: Unable to find xpath to click on element within iframe

我正在使用这段代码,但无法让它与 xpath 一起工作:

browser = webdriver.Chrome(chrome_path)
browser.get("https://planetradio.co.uk/cool-fm")
time.sleep(5)
browser.find_element_by_xpath('//*[@id="notice"]/div[4]/button[2]').click()

元素 ACCEPT ALL 中,因此您必须:

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

  • 诱导 所需的 元素可点击

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

    • 使用CSS_SELECTOR:

      driver.get('https://planetradio.co.uk/cool-fm/')
      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='ACCEPT ALL']"))).click()
      
    • 使用 XPATH:

      driver.get('https://planetradio.co.uk/cool-fm/')
      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='ACCEPT ALL']"))).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