How to Get Page Source in Selenium Java
Selenium is an
open-source
web-based automation
tool that is implemented using a web driver. We will be using geckodriver
because Selenium 3
enables geckodriver as the default WebDriver implementation for
Firefox.
Pre-requisites:
- geckodriver.exe
- maven dependency selenium
<dependency> <groupid>org.seleniumhq.selenium</groupid> <artifactid>selenium-java</artifactid> <version>4.1.1</version> </dependency>
Steps:
Getting page sources takes 3 simple steps:
-
Set
webdriver.gecko.driver
and its'path
as a system property. - Set the firefox diver and browse to the website.
- Get the page source using built-in function of Webdriver.
Let’s see all the above steps in the code. We will use
Webelment.getPageSource()
function to get source code of the browsed page.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class GetPageSource { public static String GECKODRIVER_PATH = "F:\\WORK\\SeleniumShortTasks\\PageSource\\src\\main\\resources\\geckodriver.exe"; public static Random r = new Random(); public static void main(String[] args) { //set firefox webdriver System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH); WebDriver driver = new FirefoxDriver(); //get the firefox browser & Browse the Website String siteLink = "https://audio-joiner.com/"; driver.get(siteLink); //Get page source as String String pageSource = driver.getPageSource() ; System.out.println("Page Source : "+pageSource); } }
Output:
All resources used in this tutorial are attached:
- source code
- geckdriver.exe
Comments
Post a Comment