StackTrace
StackTrace

Reputation: 231

Getting xpath or CSS for element of Body within iframe tag

Given the following html markup structure:

<body>
  <div id=Body>
   <div>
    <iframe>//Data within iframe is generated dynamically
     <html>
      <head></head>
       <body>
        <div id="abcdef">
         <div></div>
         <div></div>
         <div></div>
       </body>
     </html>
    </iframe>
  </div>
 <body>

I want to access the xpath and CSS Selector for <div id="abcdef"> but I am not able to, as it is referring to the internal <html> tag as different frame.

Upvotes: 0

Views: 9753

Answers (2)

StackTrace
StackTrace

Reputation: 231

Grabbing the iframe like below worked,

driver.switch_to.frame(driver.find_element_by_id('frameid'));

To refer more methods, Here's a link

Switching to frame, enables you to access all the elements directly.

for above example xpath will be: //*[@id='abcdef']

Upvotes: 1

SgtPooki
SgtPooki

Reputation: 11649

Using

<body>
    <div id="Body">
    <iframe>//Data within iframe is generated dynamically
        <html>
            <head></head>
            <body>
                <div id="abcdef">
                    <div></div>
                    <div></div>
                    <div></div>
                </div>
            </body>
        </html>
    </iframe>
    </div>
</body>

I was able to successfully select that element with:

//iframe//div[@id = 'abcdef']

Try it out here: http://www.freeformatter.com/xpath-tester.html

However, this is not going to work in the DOM, because of iframe security restrictions. This xpath is correct, but you can test in the chrome dev console with

$x("//iframe//div[@id = 'abcdef']")

and see that you do not get any results. When dealing with HTML documents, your browsers are going to restrict your access to iframes, so you will need to actually grab the iframe, read the html, and then search that html. You will not be able to use an xpath or css selector, as far as I am aware, without getting the content of the iframe and then searching through it as it's own document/element.

Upvotes: 1

Related Questions