Skip to content Skip to sidebar Skip to footer

How To Change Geolocation Of Chrome Selenium Driver In Python?

I am trying to trick the chromedriver to make it believe that it is running in a different city. Under normal circumstances, this can easily be done manually as shown in a quick di

Solution 1:

You can do this by importing Selenium DevTools package. Please refer below for complete java code sample:

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;

publicvoidgeoLocationTest(){
  ChromeDriverdriver=newChromeDriver();
  Mapcoordinates=newHashMap()
  {{
      put("latitude", 50.2334);
      put("longitude", 0.2334);
      put("accuracy", 1);
  }};    
  driver.executeCdpCommand("Emulation.setGeolocationOverride", coordinates);
  driver.get("<your site url>");
}  

Reference : Selenium Documentation

Solution 2:

Try this code below :

driver.execute_script("window.navigator.geolocation.getCurrentPosition=function(success){"+"var position = {\"coords\" : {\"latitude\": \"555\",\"longitude\": \"999\"}};"+"success(position);}");

    print(driver.execute_script("var positionStr=\"\";"+"window.navigator.geolocation.getCurrentPosition(function(pos){positionStr=pos.coords.latitude+\":\"+pos.coords.longitude});"+"return positionStr;"))

Solution 3:

In search for a solution to the same problem I also came across the already postet scripts. While I am yet to find a solution, I assume that the scripts don't work because they do not change the sensors permanently. The sensors are only changed for that one specific call of window.navigator.geolocation.getCurrentPosition.

The website (in this case google) will later call the same function but with the regular (unchanged) geolocation. Happy to hear solutions to permanently change the sensors to then also affect future geolocation requests.

Solution 4:

This Can be Done Using Selenium 4.

HashMap<String ,Object> coordinate = new HashMap<String ,Object>();
        coordinate.put("latitude", 39.913818);
        coordinate.put("longitude", 116.363625);
        coordinate.put("accuracy", 1);
    ((ChromeDriver)driver).executeCdpCommand("Emulation.setGeolocationOverride",coordinate);
        driver.navigate().to("URL");

Post a Comment for "How To Change Geolocation Of Chrome Selenium Driver In Python?"