Search code examples
pythonseleniumselenium-webdriverwebdriverselenium-chromedriver

Python Selenium - override geolocation not working


I'm trying to navigate to Google Maps using selenium webdriver while emulating a different location in Python.

This doesn't seem to work:

from selenium import webdriver

driver = webdriver.Chrome()

params = {
    "latitude": 42.1408845,
    "longitude": -72.5033907,
    "accuracy": 100
}
driver.execute_cdp_cmd("Emulation.setGeolocationOverride", params)
driver.get("https://maps.google.com")

When Google Maps opens, I get my current location rather than the one set in params.

What am I doing wrong? Using Selenium 4.


Solution

  • Actually you are almost there. you just need to click the your location button. using this:

    from selenium import webdriver
    from selenium.webdriver.common.by import By #added
    from selenium.webdriver.support.ui import WebDriverWait #added
    from selenium.webdriver.support import expected_conditions as EC #added
    
    driver = webdriver.Chrome()
    
    params = {
        "latitude": 42.1408845,
        "longitude": -72.5033907,
        "accuracy": 100
    }
    driver.execute_cdp_cmd("Emulation.setGeolocationOverride", params)
    driver.get("https://maps.google.com")
    element = WebDriverWait(driver, 20).until(
     EC.presence_of_element_located((By.ID, "widget-mylocation"))) #added
    element.click(); #added