How to Change User Agent In Selenium Webdriver

Hi all, in this post I will show how to change user agent for your test automation projects by using User-Agent Switcher add-on and selenium webdriver for Firefox and Chrome.

Changing User Agent for Firefox

1) First you should add User-Aget Switcher to your Firefox browser.

2) Save all device list to desktop and import it as shown below.

3) Go to Tools-> Default User Agent -> Edit User Agents

Then select Mobile Devices -> Devices -> HTC -> One M9 – Android 6.0 -Chrome 52.0 and then click Edit.

Then, you can see the user agent value of HTC One M9 as shown below. Copy and save these value for user agent manipulation in our selenium webdriver test automation code.

Test Scenario:

  • Go to www.amazon.com
  • Write “Sony Headphones” to the search bar.
  • Click search button
  • Wait until first search result’s image is visible
  • Write first search element’s text to the console

Test Code:

import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.net.MalformedURLException;

/**
 * Created by onurb on 29-Nov-16.
 */
public class MobileWebTestFirefox {

    private static WebDriver driver;
    private WebDriverWait wait = new WebDriverWait(driver,10);

    @BeforeClass
    public static void setup () throws MalformedURLException {
        //Declare Firefox Driver Location
        String geckoDriverLocation = "C:\\Selenium\\drivers\\firefox\\geckodriver.exe";
        System.out.println("Gecko Driver: " + geckoDriverLocation );
        System.setProperty("webdriver.gecko.driver", geckoDriverLocation);

        //Firefox Profile Settings
        FirefoxProfile profile = new FirefoxProfile();

        //******************************************************
        // This is Optional For My Work Laptop Security Settings
        //******************************************************
        //Accept Untrusted Certificates
        profile.setAcceptUntrustedCertificates(true);
        profile.setAssumeUntrustedCertificateIssuer(false);
        //Use No Proxy Settings
        profile.setPreference("network.proxy.type", 0);
        //******************************************************
        //******************************************************

        //Change User Agent to HTC ONE M9
        profile.setPreference("general.useragent.override", "Mozilla/5.0 (Linux; Android 6.0; HTC One M9 Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36"); 
        driver = new FirefoxDriver(profile);
    }

    @Test
    public void mobileWebTestFirefox () throws InterruptedException {
        //Go To Amazon.com
        driver.navigate().to("http://www.amazon.com/");

        //Get search bar and search button
        WebElement searchBar = driver.findElement(By.id("nav-search-keywords"));
        WebElement searchButton = driver.findElement(By.xpath("./*//*[fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][@id='nav-search-form']/div[1]/div/input"));
        
        //Write Sony Headphones to the search bar and click search button
        searchBar.sendKeys("Sony Headphones");
        searchButton.click();
        
        //Wait until first element image is visible
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='resultItems']/li[1]/a/div/div[1]/div/img")));
        
        //Get first element's text and write it to the console
        String firstSearchElementText = driver.findElement(By.xpath(".//*[@id='resultItems']/li[1]/a/div/div[2]/h5")).getText();
        System.out.println("First Search Element Name: " + firstSearchElementText);
    }

    @AfterClass
    public static void quitDriver() {
        driver.quit();
    }
}

Changing User Agent for Chrome

1) First you should add User-Aget Switcher to your Chrome browser.

2) Go to User-Agent Switcher settings at Chrome extensions section and get desired agent’s information.

user agent

The test scenario is the same and the code is for Chrome browser is shown below.

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 * Created by onurb on 29-Nov-16.
 */
public class MobileWebTestChrome {

    private static WebDriver driver;
    private WebDriverWait wait = new WebDriverWait(driver,10);

    @BeforeClass
    public static void setup () {
        //Chrome Driver Decleration
        String chromeDriverLocation = "C:\\Selenium\\drivers\\chrome\\chromedriver.exe";
        System.out.println("Chrome Driver: " + chromeDriverLocation );
        System.setProperty("webdriver.chrome.driver", chromeDriverLocation);

        //Chrome Options
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--user-agent=Mozilla/5.0 (Linux; Android 6.0; HTC One M9 Build/MRA58K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36");
        options.addArguments("--start-maximized");
        driver = new ChromeDriver(options);
    }

    @Test
    public void mobileWebTestChrome () throws InterruptedException {
        //Go To Amazon.com
        driver.navigate().to("http://www.amazon.com/");

        //Get search bar and search button
        WebElement searchBar = driver.findElement(By.id("nav-search-keywords"));
        WebElement searchButton = driver.findElement(By.xpath("./*//*[@id='nav-search-form']/div[1]/div/input"));

        //Write Sony Headphones to the search bar and click search button
        searchBar.sendKeys("Sony Headphones");
        searchButton.click();

        //Wait until first element image is visible
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='resultItems']/li[1]/a/div/div[1]/div/img")));

        //Get first element's text and write it to the console
        String firstSearchElementText = driver.findElement(By.xpath(".//*[@id='resultItems']/li[1]/a/div/div[2]/h5")).getText();
        System.out.println("First Search Element Name: " + firstSearchElementText);
    }

    @AfterClass
    public static void quitDriver() {
        driver.quit();
    }

}

Github: https://github.com/swtestacademy/GridTests/tree/master/src/test/java/grid/MobileUserAgent

The end!
-Onur

2 thoughts on “How to Change User Agent In Selenium Webdriver”

  1. I have been trying to set the User Agent for Safari. I have not found a solution. Do you know if it is possible to pass User Agent configuration information to SafariDriver/Safari using Selenium?

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.