Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium Webdriver: finding #document element

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>
like image 877
user3766359 Avatar asked Jun 23 '14 07:06

user3766359


People also ask

How do I find class in Selenium?

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.

How do I find my Selenium ID?

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'].


1 Answers

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.

like image 85
aychedee Avatar answered Sep 21 '22 19:09

aychedee