Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Inspect Element code using Selenium WebDriver

I'm working in selenium with Firefox browser.

The Html code shown in View Source (CTRL+U) is different from the html code i see when inspecting the elements in Firefox.

When i run the driver.getPageSource() i only get the View source (CTRL + U) codes.

Is there is any way to access the Inspect element code instead of View source code?

like image 418
user2782522 Avatar asked Oct 10 '14 19:10

user2782522


2 Answers

I think your question is answered here.

The View Source html is what is sent by the server. I think of it as compile time html, or the initial state of the DOM.

The Inspect Element html could have been updated by ajax responses or javascript so will not necessarily be the same. I think of it as runtime html, or the current state of the DOM.

The GetAttribute() method queries the current DOM element state. You can return a particular html attribute value directly

webElement.GetAttribute("class")

or get the whole html string.

webElement.GetAttribute("innerHTML")
like image 127
John O. Avatar answered Sep 28 '22 10:09

John O.


There are some fundamental difference between the markup shown through View Source i.e. using ctrl + U and the markup shown through Inspector i.e. using ctrl + shift + I.

Both the methods are two different browser features which allows users to look at the HTML of the webpage. However, the main difference is the View Source shows the HTML that was delivered from the web server (application server) to the browser. Where as, Inspect element is a Developer Tool e.g. Chrome DevTools to look at the state of the DOM Tree after the browser has applied its error correction and after any Javascript have manipulated the DOM. Some of those activities may include:

  • HTML error correction by the browser
  • HTML normalization by the browser
  • DOM manipulation by Javascript

In short, using View Source you will observe the Javascript but not the HTML. The HTML errors may get corrected in the Inspect Elements tool. As an example:

  • With in View Source you may observe:

    <h1>The title</h2>
    
  • Whereas through Inspect Element that would have corrected as:

    <h1>The title</h1>
    

getPageSource() always returns the markup obtained through View Source.

like image 36
undetected Selenium Avatar answered Sep 28 '22 10:09

undetected Selenium