Selenium:无法单击 iframe 中的按钮

Selenium: Can't click on a button within an iframe

我用 selenium 加载了一个页面:http://www.legorafi.fr/ 接下来,我尝试单击“Tout Accepter”按钮,但即使使用 css 选择器,它也不起作用。这是给饼干的。

我试过这样的事情:

driver.find_element_by_css_selector('').click()

这是带有文本“Tout Accepter”的蓝色按钮

我该怎么办?

首先切换到横幅框架,然后点击接受按钮:

from selenium import webdriver

url = "http://www.legorafi.fr/"
driver = webdriver.Chrome()
driver.get(url)
driver.switch_to.frame(2)
button = "/html/body/div/div/article/div/aside/section[1]/button"      
driver.find_element_by_xpath(button).click()

(我使用 XPath 单击按钮,但这只是个人喜好)

希望对您有所帮助!

该元素存在于 iframe 中,您需要切换 iframe 才能访问该元素。

引入 WebDriverWait() 并等待 frame_to_be_available_and_switch_to_it() 和跟随 css 选择器

诱导 WebDriverWait() 并等待 element_to_be_clickable() 和跟随 xpath

driver.get("http://www.legorafi.fr/")
WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"#appconsent>iframe")))
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//span[text()='Tout Accepter']"))).click()

您需要导入以下库

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

元素 Tout Accepter<iframe> 中,因此您必须:

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

  • 诱导 所需的 元素可点击

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

  • 使用CSS_SELECTOR:

    driver.get('http://www.legorafi.fr/')
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"div#appconsent>iframe")))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.button--filled>span.baseText"))).click()
    
  • 使用XPATH:

    driver.get('http://www.legorafi.fr/')
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//div[@id='appconsent']/iframe")))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'button--filled')]/span[contains(@class, 'baseText')]"))).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