Howto Mock Geolocation in Headless Chrome
This is in Python:
1import time,random
2from selenium.webdriver import Chrome, ChromeOptions
3
4chrome_options = ChromeOptions()
5chrome_options.add_argument("--disable-extensions")
6chrome_options.add_argument("--disable-gpu")
7chrome_options.add_argument("--no-sandbox")
8chrome_options.add_argument('--disable-dev-shm-usage')
9chrome_options.add_argument("--headless")
10chrome_options.add_experimental_option("prefs", { "profile.default_content_setting_values.geolocation": 1})
11driver = Chrome(options=chrome_options)
12
13# Honolulu: 21.3281792,-157.8691131
14# Mauritius: -21.0752381,57.0387649
15# South Africa: -33.914651,18.3758793
16# China: 30.2325248,120.1400391
17latitude = [21.3281792,-21.0752381,-33.914651,30.2325248]
18longitude = [-157.8691131,57.0387649,18.3758793,120.1400391]
19i = random.choice([0, 1, 2, 3])
20# this permission is for driver.get_screenshot_as_file()
21driver.execute_cdp_cmd(
22 "Browser.grantPermissions",
23 {
24 "origin": "https://www.openstreetmap.org/",
25 "permissions": ["geolocation"]
26 },
27)
28driver.execute_cdp_cmd(
29 "Emulation.setGeolocationOverride",
30 {
31 "latitude": latitude[i],
32 "longitude": longitude[i],
33 "accuracy": 100,
34 },
35)
36
37driver.get("https://www.openstreetmap.org/")
38driver.find_element_by_xpath("//span[@class='icon geolocate']").click()
39time.sleep(3) # wait for the page to be fully loaded
40driver.get_screenshot_as_file("screenshot" + str(i) + ".png")
41
42print("--DONE--")
43
44driver.quit()