Python

Faking Geolocation with Selenium, Python, Firefox.

Selenium is an excellent tool to automatize tasks through a browser, like end-to-end testing, bot creation, or as assisting in the redundant endeavours. It is sometimes needed to change the location reported by the browser. In this article we are going to see how to do with Firefox, Python and Selenium.

For this we are going to need:

Installing Firefox (Ubuntu)

sudo apt update
sudo apt install firefox

Installing Firefox Selenium driver and python package (Ubuntu)

For installing the Firefox Selenium driver, you can retrieve the last version in the official github repository

At the time this article was written, the last version was v0.24.0

# We go in the /tmp folder for disposable data operations.
cd /tmp
# We download locally the latest version (Here 64 bits version)
wget https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-linux64.tar.gz
# We extract the content
tar -xvf geckodriver-v0.24.0-linux64.tar.gz
# We install the driver
sudo cp geckodriver /usr/bin/geckodriver

Now that we have the driver installed, we need to install the python package.

For the sake of cleanliness, you can use a virtual environment.

pip3 install selenium

Faking geolocation

Before to start, you may want to check where the API locates you.

You can test and check where by going to the w3schools html5 geolocation page and clicking on the try it button.

To fake geolocation in an easy way we are going to use a property of the firefox profile which allow to set it to any value.

Open your favourite python interpreter. And let's see how do we achieve it.

from selenium import webdriver
profile = webdriver.FirefoxProfile()
# We set the coordinate of where we want to be.
profile.set_preference("geo.wifi.uri", 'data:application/json,{"location": {"lat": 38.912650, "lng":-77.036185}, "accuracy": 20.0}')
# This line is necessary to avoid to prompt for geolocation authorization.
profile.set_preference("geo.prompt.testing", True)
my_driver = webdriver.Firefox(profile)
my_driver.get("https://www.w3schools.com/html/html5_geolocation.asp")
# Let's use code to click the blue button.
my_driver.find_element_by_class_name("w3-blue").click()

That's all. You should now be in Washington congratulation. It works with almost any site, from Google maps to the w3schools small script.

One of the inconvenient of this methodology is that unfortunately, to change of location, you need to create a new instance of the driver after updating the profile.

Peace Out!

By PXke
the 27/07/2019 tags: Python, Selenium, Firefox, Geolocation, Automatization, Linux, Updated: 27/07/2019