Selenium:无法单击iframe中的按钮

2024-05-13 22:57:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试过这样的方法:

driver.find_element_by_css_selector('').click()

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

enter image description here

我该怎么办


Tags: 方法httpwwwdriverselenium选择器页面fr
3条回答

元素Tout Accepter位于<iframe>内,因此您必须:

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

  • 诱导WebDriverWait使所需的元素可单击

  • 您可以使用以下任一Locator Strategies

  • 使用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
    
  • 浏览器快照:

legorafi


参考文献

您可以在以下内容中找到一些相关讨论:

元素存在于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

首先切换到横幅框,然后单击“接受”按钮:

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单击按钮,但这只是个人喜好)

希望有帮助

相关问题 更多 >