I have been using Python's Selenium Webdriver getting elements with this HTML code. However, I could not access any of the elements inside this #document tag.
I used both
driver.find_element_by_xpath("html/body/div[@id='frame']/iframe/*")
, and I tried
elem = driver.find_element_by_tag("iframe")
, following by
elem.find_element_by_xpath
to find inner elements but failed.
I also tried to do driver.switch_to_frame(driver.find_element_by_tag("iframe"))
, following with xpath expressions to find inner elements, but it also did not work.
Frame:
<div>
<iframe>
#document
<html>
<body>
<div>
....
</div>
</body>
</html>
</iframe>
</div>
We can find an element using the attribute class name with Selenium webdriver using the locators - class name, css, or xpath. To identify the element with css, the expression should be tagname[class='value'] and the method to be used is By. cssSelector.
We can find an element using the attribute id with Selenium webdriver using the locators - id, css, or xpath. To identify the element with css, the expression should be tagname[id='value'] and the method to be used is By. cssSelector. To identify the element with xpath, the expression should be //tagname[@id='value'].
Switching to the iframe and then using the normal query methods is the correct approach to use. I use it successfully throughout a large test suite.
Remember to switch back to the default content when you've finished working inside the iframe though.
Now, to solve your problem. How are you serving the contents of the iframe? Have you literally just written the html and saved it to a file or are you looking at an example site. You might find that the iframe doesn't actually contain the content you expect. Try this.
from selenium.webdriver import Firefox
b = Firefox()
b.get('localhost:8000') # or wherever you are serving this html from
iframe = b.find_element_by_css_selector('iframe')
b.switch_to_frame(iframe)
print b.page_source
That will be the html inside the iframe. Is the contents what you expect? Or is it mainly empty. If it's empty then I suspect it's because you need to serve the contents of the iframe separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With