
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Page Source in Browser Using Selenium
We can get page source as it is in browser using Selenium webdriver using the getPageSource method. It allows us to obtain the code of the page source.
Syntax
String p = driver.getPageSource();
We can also obtain the page source by identifying the body tag with the help offindElement method and then apply the getText method on it. The parameter By.tagName is passed as a parameter to the findElement method.
Syntax
WebElement l= driver.findElement(By.tagName("body")); String p = l.getText();
Example
Code Implementation with getPageSource
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class PgSrc{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get ("https://www.tutorialspoint.com/about/about_careers.htm"); //get page source String p = driver.getPageSource(); System.out.println("Page Source is : " + p); driver.close(); } }
Code Implementation with body tagname
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class PgSrcBody{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); //get page source with getText method WebElement l= driver.findElement(By.tagName("body")); String p = l.getText(); System.out.println("Page Source is : " + p); driver.close(); } }
Advertisements