Switch to an iframe through Selenium and python

2020-01-24 13:19发布

问题:

How would I switch to this iframe in selenium knowing only

<iframe name="Dialogue Window">

回答1:

You can use an XPath to locate the <iframe>:

iframe = driver.find_element_by_xpath("//iframe[@name='Dialogue Window']")

Then switch_to the <iframe>:

driver.switch_to.frame(iframe)

Here's how to switch back to the default content (out of the <iframe>):

driver.switch_to.default_content()


回答2:

As the iframe tag clearly shows the name as Dialogue Window, so here is the simple & minimal line of code to switch to the iframe:

  • As the <iframe> contains the name attribute you can :

    driver.switch_to.frame("Dialogue Window")
    
  • As an alternative you can switch with respect to the WebElement as follows :

    driver.switch_to.frame(driver.find_element_by_name('Dialogue Window'))
    
  • To switch back to the Top Window you can use the following line of code:

    driver.switch_to.default_content()