Home > Enterprise >  Python Selenium `execute_cdp_cmd` only works at the first run
Python Selenium `execute_cdp_cmd` only works at the first run

Time:11-19

I am trying to change device geolocation using Selenium Python (with Selenium wire to catch http requests) by:

from seleniumwire import webdriver

options = webdriver.EdgeOptions()
options.accept_insecure_certs = True
options.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Edge(seleniumwire_options={
                        'port': 12345, 'disable_encoding': True}, options=options)

# List of coordinates
lats = [44.55, 43.63, 52.25, 45.48, 47.35]
longs = [-77.33, -80.33, -81.62, -76.81, -84.62]

for i in range(len(lats)):
    coordinates = {
        "latitude": lats[i],
        "longitude": longs[i],
        "accuracy": i   1
    }

    driver.execute_cdp_cmd("Emulation.setGeolocationOverride", coordinates)
    driver.get(some_website)

    # I can see the coordinates passed to the `execute_cdp_cmd` changed every loop
    print(coordinates)

However, the actual geolocation will always be the first coordinates. The only way is to create a new driver at each loop but that's really bad performance. What am I doing wrong?

CodePudding user response:

Have you tried using Emulation.clearGeolocationOverride prior to calling Emulation.setGeolocationOverride?

from seleniumwire import webdriver

options = webdriver.EdgeOptions()
options.accept_insecure_certs = True
options.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Edge(seleniumwire_options={
                        'port': 12345, 'disable_encoding': True}, options=options)

# List of coordinates
lats = []
longs = []

for i in range(len(lats)):
    coordinates = {
        "latitude": lats[i],
        "longitude": longs[i],
        "accuracy": i   1
    }

    driver.execute_cdp_cmd("Emulation.clearGeolocationOverride")
    driver.execute_cdp_cmd("Emulation.setGeolocationOverride", coordinates)
    driver.get(some_website)

    print(coordinates)
  • Related