Browser Commands in Selenium

  

Browser commands in Selenium WebDriver allow you to interact with the browser as a whole, such as opening, closing, navigating, and retrieving information. Here are the most common browser commands:


List of Browser Commands:

CommandDescription
driver.get("URL")Opens a website
driver.getCurrentUrl()Returns the current URL
driver.getTitle()Returns the title of the page
driver.getPageSource()Returns the page source
driver.close()Closes the current browser window
driver.quit()Closes all browser windows and ends the session
driver.navigate().to("URL")Navigates to a specific URL
driver.navigate().back()Goes back to the previous page
driver.navigate().forward()Goes forward to the next page
driver.navigate().refresh()Refreshes the current page


Selenium Java code using browser commands

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserCommandsDemo {
    public static void main(String[] args) {

        // Set path to chromedriver
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Initialize WebDriver
        WebDriver driver = new ChromeDriver();

        // 1. Open a website
        driver.get("https://www.google.com");

        // 2. Get current URL
        String currentUrl = driver.getCurrentUrl();
        System.out.println("Current URL: " + currentUrl);

        // 3. Get page title
        String title = driver.getTitle();
        System.out.println("Page Title: " + title);

        // 4. Navigate to another URL
        driver.navigate().to("https://www.bing.com");

        // 5. Navigate back
        driver.navigate().back();

        // 6. Navigate forward
        driver.navigate().forward();

        // 7. Refresh the page
        driver.navigate().refresh();

        // 8. Get page source
        String pageSource = driver.getPageSource();
        System.out.println("Page Source Length: " + pageSource.length());

        // 9. Close the current window
        driver.close();

        // Optional: Quit the entire browser session
        // driver.quit();
    }
}

No comments:

Post a Comment