DEV Community

Cover image for Geolocation Testing With Selenium Using Examples
himanshuseth004 for LambdaTest

Posted on • Updated on • Originally published at lambdatest.com

Geolocation Testing With Selenium Using Examples

Geolocation Testing With Selenium Using Examples

A website or web application may look differently depending on the location from where it is accessed. If you are building a consumer web product that has a diverse target audience, it is essential to perform geolocation testing.

The good news is that Selenium 4 can really take you places to ensure your web-application renders perfectly from different countries, states, or even cities. Today, I am going to help you teleport from one location to another. Well, to be honest it’s going to be your browser doing that. In this article, I will be mocking browser’s geolocation using Selenium 4 alpha. Ready? Let’s do this.

iPhone simulator by LambdaTest allows you to seamlessly test your websites and webapp on latest to legacy devices, OS versions and browsers. You can also test your iOS app online on 200+ device and iOS environmets

Importance Of Geolocation Browser Testing

A lot of time, depending on the location, organization serves different content on the website. The websites being served in different countries can be in different languages or even the content or product showcased on the website might be different. To make sure that your users are being served the right content it is important to perform Gelocation testing.

Geolocation testing, as the name suggests, is a type of testing where perform tests on your website from IPs of various countries around the world. In one of our earlier blogs, we have covered the importance of geolocation browser testing in greater depth.
Shown below is the diversity of search results when search for LambdaTest is performed through an IP address from France & UK respectively.

Selenium WebdriverIO is Javascript based test automation framework built over nodeJs. Learn with this guide how to use webdriverIO to perform web automation testing.

The difference in search results clearly highlights the necessity of Geolocation testing which is a practice where testing of the website is performed from a set of IP addresses that belong to different countries around the world.

Geolocation testing is useful for checking whether product features dependent on geolocation (e.g. content) are localized as per the user location & demographics. Also called geotargeting, it is an important feature for evaluating SERP (Search Engine Result Pages). Better search rankings in turn aids in increasing conversions of the website (or web app).

Here are some of the features that can be tested with Geolocation browser testing:

  • Geofencing for driving personalized notifications

  • Localization for adapting to a particular locale

  • Testing websites across different geographies with varying internet speeds

  • Geo-blocking content for adhering to the norms of the target country

  • Geotargeting for evaluating SERP (Search Engine Result Pages)

In this tutorial, learn what is Regression testing, its importance, types, and how to perform it.

E-commerce Use Case Demonstrating Geolocation Browser Testing

To further explain the importance of Geolocation Testing with selenium. I’ll take the case of a popular e-commerce store and show you how it serves different content based on the location.

In the wake of COVID-19 pandemic, many popular e-commerce websites temporarily stopped shipping to areas (or pin codes) where a large number of COVID-19 cases were reported.

They restricted to delivering only essential items to their customers in some locations where few cases are reported, whereas they continued shipping essential & non-essential items in locations where no cases are reported.

This is where geolocation testing comes very handy as it helps in testing the tailor-made experience of the website (or app) depending on the user’s location. Here are the sample pages of a popular e-commerce website, which shows how the content and UX differs depending on the country from where the page is accessed:

Image Source: Amazon France HomePage

Image Source: Amazon Singapore Homepage

Are you wondering what is regression testing? Look no further! Our tutorial covers everything you need to know about the significance of regression testing, its various types, and how to perform it.

Geolocation Testing With Selenium 4

Selenium is a popular test automation framework that provides a number of automated browser testing capabilities. The next major public release will be Selenium 4 but there is no official announcement on the official release of the same. If you are of an inquisitive nature (like me) and enjoy experimenting with the latest features of Selenium, you should download the Selenium 4 (Alpha) version. At the time of writing this blog, the latest Selenium 4 Alpha version was Selenium 4.0.0-alpha-6.

We have already covered features that you can expect from Selenium 4 Alpha , along with usage of relative locators in Selenium 4. For demonstrating geolocation testing with Selenium, we would be using the Python language; further details about Selenium 4 for Python are available here.

*Bonus Tip *— If you are using Selenium Java and want to try geolocation testing in Selenium, you can directly navigate here☺. Before heading to the implementation, we recommend you to go through this section to get a hold of the test case used for demonstration.

Environment Setup For Selenium 4

For installing Selenium 4.0.0-alpha-6 in your system, execute the following command on the terminal:

pip install selenium==4.0.0a6
Enter fullscreen mode Exit fullscreen mode

Post the completion, you can further execute the following command to verify whether Selenium 4 installation was successful (or not)

$ python -c "import selenium; print(selenium.__version__)"
4.0.0a5
1
2
$ python -c "import selenium; print(selenium.__version__)"
4.0.0a5
Enter fullscreen mode Exit fullscreen mode

In the latest release of Selenium 4, they have provided access to Chrome DevTools and CDP (Chrome DevTools Protocol). These new set of features can be used for performing geolocation testing with Selenium.

As Chrome DevTools is used, the browser under test should be Google Chrome. We recommend you to download Chrome if you plan to execute the sample code provided further in the blog. You also have to install Selenium WebDriver for Chrome from here.

With installation of Selenium 4 (Alpha), Google Chrome, and Chrome WebDriver; your environment is all set for geolocation testing with Selenium.

Geolocation Testing With Selenium 4 Using Pytest

For mocking (or faking) the geolocation, you first need to supply the latitude and longitude of the mock location. The same can be obtained using Google Maps where you have to search for the desired location.

Copy the latitude & longitude from the URL. The first number is the latitude (i.e. 42.1408845) and the second number is the longitude (-72.5033907).

For mocking the location to the one mentioned above, we use executeCdpCommand which is available with Selenium 4. DevTools Protocol website has more information about the command name that needs to be passed to executeCdpCommand.

As the current geolocation position needs to be overridden, we use the Emulation.setGeolocationOverride command.

The command takes three parameters — Latitude, Longitude, and Accuracy. Using Google maps, we have already found the coordinates (Latitude: 42.1408845, Longitude: -72.5033907) that have to be used for geolocation testing with Selenium. Any non-zero number should suffice for accuracy. These parameters basically form the map coordinates against which the location will be mocked.

For geolocation testing with Selenium, we search for Denny’s restaurant using the location coordinates that we derived from Google Maps.

Implementation

#Performing Geolocation Testing With Selenium Using Python For Selenium Test Automation
import pytest
import pytest_html
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time
from time import sleep
import sys
import urllib3
import warnings

class Test_Scenario_1:
    def test_1(self):
        driver = webdriver.Chrome()

        self.latitude = 42.1408845
        self.longitude = -72.5033907
        self.accuracy = 100

        driver.maximize_window()
        driver.execute_cdp_cmd("Emulation.setGeolocationOverride", {
            "latitude": self.latitude,
            "longitude": self.longitude,
            "accuracy": self.accuracy
    })

        driver.get("https://locations.dennys.com/search.html/")

        time.sleep(10)

        location_icon = driver.find_element_by_css_selector(".icon-geolocate")
        time.sleep(10)
        location_icon.click()

        time.sleep(10)
        print("Geolocation testing with Selenium is complete")
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

*Step 1 *— To get started, we create a Chrome WebDriver instance as the testing is performed on the Chrome browser. If you want to learn more about testing with ChromeDriver, you can refer to the blog linked.

driver = webdriver.Chrome()
driver.get("https://locations.dennys.com/search.html/")
Enter fullscreen mode Exit fullscreen mode

*Step 2 *— The necessary information for mocking the geolocation (i.e. latitude, longitude, and accuracy) are defined. That data is passed to the newly introduced Selenium API execute_cdp_cmd. The first parameter to the API is the command to override the existing geolocation (i.e. Emulation.setGeolocationOverride) and the second parameter is the geolocation coordinates.

#execute_cdp_cmd for Geolocation testing with Selenium
self.latitude = 42.1408845
self.longitude = -72.5033907
self.accuracy = 100

driver.maximize_window()
driver.execute_cdp_cmd("Emulation.setGeolocationOverride", {
 "latitude": self.latitude,
      "longitude": self.longitude,
      "accuracy": self.accuracy
Enter fullscreen mode Exit fullscreen mode

*Step 3 *— Now that the mocked geolocation information is available, we trigger the location search for nearby Denny’s restaurants as per the supplied information. Chrome Inspection Tools is used for locating the web element (.icon-geolocate) using CSS Selector property.

location_icon = driver.find_element_by_css_selector(".icon-geolocate")
time.sleep(10)
location_icon.click()
Enter fullscreen mode Exit fullscreen mode

Once the element is located, a click is performed for triggering location based search for Denny’s restaurants.

Execution

For executing the code for Geolocation testing with Selenium, I’ll use the pytest command with verbosity on.

pytest -v Mocking_geolocation_Selenium_4.py
Enter fullscreen mode Exit fullscreen mode

Shown below in this Selenium tutorial on browser location test is the execution snapshot captured from the terminal.

Here is the search result of nearby Denny’s restaurants as per the latitude and longitude supplied in the implementation for Geolocation testing with Selenium.

Geolocation testing with Selenium can also be performed using the Java Language as support is available for that language as well. Mocking geolocation with Selenium 4 is extremely useful for testing product features that are dependent on the user’s location.

Our tutorial is the perfect resource to understand the concept of regression testing in-depth. Learn about the importance of regression testing, its various types, and how to perform a regression test with ease.

Geolocation Testing With Selenium 4 Using TestNG

Using Maven, I’ll update the pom.xml for adding the following essential dependencies:

  • selenium-chrome-driver (version — 4.0.0-alpha-6)

  • selenium-java (version — 4.0.0-alpha-6)

The entries can be directly added in your project’s pom.xml so that you can directly get geolocation with Selenium Java working on your machine. Here is the complete pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.selenium4</groupId>
  <artifactId>geolocation</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>geolocation</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
        <!-- https://mvnrepository.com/artifact/com.github.lambdatest/lambdatest-tunnel-binary -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.0.0-alpha-6</version>
        </dependency>
  <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>4.0.0-alpha-6</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.8</version>
        </dependency>

        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.28</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

<build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.4</version>
            </plugin>
        </plugins>
    </build>

</project>  
Enter fullscreen mode Exit fullscreen mode

GeoLocationTest.java

package org.selenium4;

import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.Map;
import java.util.*;
import io.github.bonigarcia.wdm.WebDriverManager;

public class GeoLocationTest {
    protected static ChromeDriver driver;
    String URL = "https://locations.dennys.com/search.html/";

    @BeforeClass
    public void testSetUp() {
        /* System.setProperty("webdriver.chrome.driver", "C:\\EdgeDriver\\chromedriver.exe"); */
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
    }

    @Test
    public void test_Selenium4_Geolocation() throws InterruptedException {
        Map< String,Object> coordinates =  
                new HashMap< String,Object>();

        /* Create a hashmap for latitude, longitude, and accuracy as needed by Google Maps */
        coordinates.put("latitude", 42.1408845); 
        coordinates.put("longitude", -72.5033907);
        coordinates.put("accuracy", 100);

        /* Command to emulate Geolocation */
        driver.executeCdpCommand("Emulation.setGeolocationOverride", coordinates);
        driver.navigate().to(URL);
        driver.manage().window().maximize();

        /* driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); */
        /* Not a good programming practice, added for demonstration */
        Thread.sleep(5000);

        WebElement location_icon = driver.findElement(By.cssSelector(".icon-geolocate"));
        Thread.sleep(2000);
        location_icon.click();

        Thread.sleep(6000);
        System.out.println("Geolocation testing with Selenium is complete");
    }

    @AfterClass
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code WalkThrough

*Step 1 *— The testng framework is used for testing. We import the necessary packages of testng.

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
Enter fullscreen mode Exit fullscreen mode

*Step 2 *— The method implemented under @BeforeClass annotation sets up the ChromeDriver. For using CDP methods, we have declared the driver as ChromeDriver.

public class GeoLocationTest {
    protected static ChromeDriver driver;
    String URL = "https://locations.dennys.com/search.html/";

    @BeforeClass
    public void testSetUp() {
        /* System.setProperty("webdriver.chrome.driver", "C:\\EdgeDriver\\chromedriver.exe"); */
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
    }
Enter fullscreen mode Exit fullscreen mode

Step 3 *— Test method is implemented under *@ Test annotation. HashMap, a map-based class for storing Key and Value pairs (HashMap) is used for storing the latitude, longitude, and accuracy; the parameters required for Google Maps.

@Test
    public void test_Selenium4_Geolocation() throws InterruptedException {
        Map< String,Object> coordinates =  
                new HashMap< String,Object>();

        /* Create a hashmap for latitude, longitude, and accuracy as needed by Google Maps */
        coordinates.put("latitude", 42.1408845); 
        coordinates.put("longitude", -72.5033907);
        coordinates.put("accuracy", 100);  
Enter fullscreen mode Exit fullscreen mode

*Step 4 *— The executeCdpCommand, a new method added in the ChromeDriver class is used for mocking the geolocation. The input arguments to the method are command name (i.e. Emulation.setGeolocationOverride) and map of parameters (i.e. coordinates).

/* Command to emulate Geolocation */
String URL = "https://locations.dennys.com/search.html/";

driver.executeCdpCommand("Emulation.setGeolocationOverride", coordinates);
Enter fullscreen mode Exit fullscreen mode

*Step 5 *— We navigate to the target URL and use Selenium WebDriver APIs for performing a ‘click’ operation on the search button on the target URL.

driver.navigate().to(URL);
driver.manage().window().maximize();
/* driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); */
/* Not a good programming practice, added for demonstration */
Thread.sleep(5000);

WebElement location_icon = driver.findElement(By.cssSelector(".icon-geolocate"));
Thread.sleep(2000);
location_icon.click();
Enter fullscreen mode Exit fullscreen mode

Blocking delays (not a recommended programming practice) have been added for testing and observing the output.

Step 6 *— The implementation of the method under *@ AfterClass annotation frees the resources allocated by the instantiated Chrome WebDriver.

@AfterClass
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
Enter fullscreen mode Exit fullscreen mode

Execution

In the Maven project in Eclipse, right-click on the Java File (i.e. GeoLocationTest.java) and Run as ‘TestNG Test’.

The test would instantiate the Chrome browser and perform the desired test that mocks geolocation. Shown below is the execution output:

In order to learn more about browser automation with Selenium Java, you can refer to the article linked.

Geolocation Testing With Selenium 4 On Cloud-based Selenium Grid

LambdaTest provides cross browser testing on the Selenium Grid Using which you can perform automated browser testing across 3000+ combinations of real browsers and operating systems online.

Unlike geolocation testing on a local Selenium grid which is limited only to geolocation coordinates (i.e. latitude and longitude); LambdaTest offers browser compatibility testing experience for different countries in the world. Along with real-time testing on the platform, geolocation testing on Selenium Grid can be performed using Desired Browser Capabilities for Selenium 4.

Shown below is the browser capabilities with geolocation country set to United States.

capabilities = {
        "user" : "user-name",
        "accessKey" : "access-key",
        "build" : "your build name",
        "name" : "your test name",
        "platformName" : "Windows 10",
        "browserName" : "Chrome",
        "browserVersion" : "83.0",
        "geoLocation" : "US"
}
Enter fullscreen mode Exit fullscreen mode

Using LambdaTest, you can perform geolocation testing of your website (or web app) across 53 different countries. The drop-down for Geolocation is available for Selenium and Selenium 4.

We have covered Selenium 4 capabilities, geolocation testing using Selenium on LambdaTest Grid.

Perform browser automation testing on the most powerful cloud infrastructure. Leverage LambdaTest automation testing for faster, reliable and scalable experience on cloud.

It’s a Wrap!

Geolocation browser testing is important for testing product features that depend on the location from where the website (or web app) is accessed. Thorough geolocation browser testing will also help in improving your website’s ranking on popular search engines.

Geolocation testing with Selenium 4 helps in automating the testing of your website against different geolocations i.e. latitude and longitude. Access to Chrome DevTools and CDP (Chrome DevTools Protocol) is provided in Selenium 4 and that is the key enabler for geolocation browser testing using Selenium.

LambdaTest helps you automate geolocation browser testing from 53 countries across the globe. Geolocation testing on the platform can be performed through real-time testing, as well as, automated browser testing using Selenium 4.

Top comments (0)