Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 diagram

Here

Then, when a google search is done, the new coordinates are used, and the results that would normally originate from that location are displayed. You can confirm that this worked when you look at the bottom of a Google search page as seen

Here.

However, Selenium can only control what the browser displays, not the browser in itself. I cannot tell Selenium to automatically click the buttons needed to change the coordinates. I tried the solutions posted here but that is not meant for Python, and even after I tried to adapt the script, nothing seemed to happen.

Is there a browser.execute_script() argument that could work, or is this the wrong way to change the geolocation?

like image 513
Ari Avatar asked Dec 14 '18 02:12

Ari


People also ask

How do I change my browser driver path in Selenium?

Go to the terminal and type the command: sudo nano /etc/paths. Enter the password. At the bottom of the file, add the path of your ChromeDriver. Type Y to save.


2 Answers

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;

public void geoLocationTest(){
  ChromeDriver driver = new ChromeDriver();
  Map coordinates = new HashMap()
  {{
      put("latitude", 50.2334);
      put("longitude", 0.2334);
      put("accuracy", 1);
  }};    
  driver.executeCdpCommand("Emulation.setGeolocationOverride", coordinates);
  driver.get("<your site url>");
}  

Reference : Selenium Documentation

like image 59
Vijendran Selvarajah Avatar answered Oct 16 '22 13:10

Vijendran Selvarajah


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;"))
like image 45
An Nguyen Avatar answered Oct 16 '22 14:10

An Nguyen