in selenium web driver how to choose the correct iframe

I just checked in the website, they (the elements you are looking for) are NOT in any iframe tag.

Following code worked for me (changed to xpath, no need to switch):

driver.find_element_by_xpath("//span[contains(text(),'Cash Flow')]").click()
driver.find_element_by_xpath("//span[contains(text(),'Balance Sheet')]").click()
driver.find_element_by_xpath("//span[contains(text(),'Quarterly')]").click()

Note: It might be the reason that for “Financials”, parent tag is a which represent a link, but for other elements (Cash Flow, Balance sheet), parent tag is div which is not a link tag. so find_element_by_link_text might not have been worked.


Switching between iframes:

You have to switch to the frame in which the element is present before we try to identify it.

Lets assume, your element is inside 3 iframes as follows:

<iframe name="frame1">
  <iframe name="frame2">
     <iframe name="frame3">
        <span>CashFlow</span> <! Span element is inside of 3 iframes>
    </iframe>
    <span>balance sheet> <! Span element is inside of 2 iframes>
  </iframe>
</iframe>

Now, if you want to identify CashFlow which is inside the three iFrames:

    driver.switch_to_frame(driver.find_element_by_name("frame1")) // here, you can provide WebElement representing the iFrame or the index.
    driver.switch_to_frame(driver.find_element_by_name("frame2"))
    driver.switch_to_frame(driver.find_element_by_name("frame3"))
    driver.find_element_by_link_text("CachFlow")

    # switch to default frame before you again try find some other element which is not in the same frame (frame3)

   driver.switch_to_default_content()

   # then navigate to the frame that you want to indentify the element:
   driver.switch_to_frame(driver.find_element_by_name("frame1")) 
   driver.switch_to_frame(driver.find_element_by_name("frame2"))
   driver.find_element_by_link_text("balance sheet")

  # switch to default content again
  driver.switch_to_default_content()

Note: I used Frame References instead of indexes as you mentioned there are 9 iFrames. so, using indexes would be confusing. If you can’t identify frameElement, then only go for indices.

Reference:

  1. http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.switch_to_frame

Leave a Comment