如何在 Selenium 和 Python 中的 iframe 之间切换

How to change between iframes in Selenium and Python

我试图了解如何在 selenium webdriver 中的 iframe 之间进行更改,但我无法弄清楚。 在前面的图像中,是我要切换到的 iframe:

快照:

 //iframe[@class='viewer pbi-frame']

应该是使用 driver.switch_to.frame()

的简单 xpath

或者

 //iframe[@title='Power BI Report Viewer']

要切换到 iframe,您可以使用如下代码:

driver.switch_to.frame(driver.find_element_by_css_selector("//iframe[@title='PowerBi Report Viewer']"))

在 iframe 中完成工作后,您必须使用

切换回默认内容
driver.switch_to.default_content()

该网站是 based, so to switch within the ,因此您必须:

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

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

    • 使用CSS_SELECTOR:

      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='PowerBi Report Viewer']")))
      
    • 使用 XPATH:

      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='PowerBi Report Viewer']")))
      
  • 注意:您必须添加以下导入:

     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