如何使用 Selenium 和 Python 单击 iframe 内的按钮

How can I click on a button inside an iframe using Selenium and Python

我正在尝试点击 iframe 中的按钮 "Administration",但出现此错误:

selenium.common.exceptions.TimeoutException: Message:

Python 我使用的代码:

main = driver.find_element_by_xpath("//div[@class='main absolute']")
main.click()
driver.switch_to.frame("tab_Welcome")
button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.wah-global-ask-banner-item div.wah-global-ask-banner-item-title.wah-global-ask-banner-item-title-paa")))
button.click()

HTML:

诱导 WebDriverWaitframe_to_be_available_and_switch_to_it() 引入 WebDriverWaitelement_to_be_clickable() 并遵循 XPATH。

main = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='main absolute']")))
main.click()
WebDriverWait(driver,20).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"frame_Welcome")))
button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[text()='Administration']")))
button.click()

您似乎正在使用它的 ID 切换到 iframe,但您需要通过名称切换到它。

所以而不是 driver.switch_to.frame("tab_Welcome")

你应该试试driver.switch_to.frame("frame_Welcome")

希望对您有所帮助。

To click() 在文本为 Administration 的元素上,因为所需的元素在 <iframe> 中,所以你必须:

  • 诱导 WebDriverWait 以获得所需的 框架并切换到它
  • 诱导 WebDriverWait 使所需的 元素可点击
  • 您可以使用以下任一项:

    • CSS_SELECTOR:

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.iframe-content#tab_Welcome")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.wah-global-ask-banner-item-title.wah-global-ask-banner-item-title-paa"))).click()
      
    • XPATH:

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='iframe-content' and @id='tab_Welcome']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='wah-global-ask-banner-item-title wah-global-ask-banner-item-title-paa' and text()='Administration']"))).click()
      
    • 注意:您必须添加以下导入:

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

Here you can find a relevant discussion on

def find_all_iframes(driver):
    iframes = driver.find_elements_by_xpath("//iframe")
    for index, iframe in enumerate(iframes):
        # Your sweet business logic applied to iframe goes here.
        driver.switch_to.frame(index)
        find_all_iframes(driver)
        driver.switch_to.parent_frame()