如何在Python中更改Chrome Selenium驱动程序的地理位置?

10

我正在尝试欺骗chromedriver,使其认为它是在另一个城市运行。在正常情况下,可以通过如下快速图解手动轻松完成此操作:

这里

然后,在进行谷歌搜索时,会使用新的坐标,并显示通常源自该位置的结果。当您查看Google搜索页面底部时,确认此方法是否有效,如下所示:

这里.

然而,Selenium 只能控制浏览器显示,而不能控制浏览器本身。我无法告诉 Selenium 自动点击改变坐标所需的按钮。我尝试了这里发布的方案,但那不适用于 Python,即使我尝试适应脚本,仍然没有任何反应。

是否有 browser.execute_script() 参数可用,或者这种方式更改地理位置是错误的?


我建议直接在这里添加图片,这样问题就永远不会过时。因此,这个问题值得点赞。 - AER
如果您正在与另一个应用程序交互,可能与用户权限有关? - AER
@Ari,你已经解决了地理位置更改的问题吗?我也在寻找同样的解决方案,但是发现这似乎不可能。 - Apalabrados
4个回答

2

您可以通过导入Selenium DevTools包来实现此操作。 以下是完整的Java代码示例:

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


它适用于哪个版本的Selenium? - The Dan

1

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;"))

虽然我确实看到了打印语句输出了我要求的坐标,但对Google搜索结果没有任何影响。通常情况下,使用传感器方法时,转到结果的下一页会更新位置。当我尝试使用这个execute_script时,没有任何变化,它仍然显示我的实际位置。需要注意的是,在这里你可以看到Google根据我的网络地址获取了我的位置,而使用传感器方法,则得到了“从此计算机报告的位置”。有没有办法阻止Chrome看到我的IP地址? - Ari
我建议您使用虚假IP应用程序。 - An Nguyen

0
在寻找解决同样问题的方案时,我也遇到了已经发布的脚本。虽然我还没有找到解决方案,但我认为这些脚本不起作用是因为它们不能永久改变传感器。传感器仅在调用window.navigator.geolocation.getCurrentPosition时更改一次。

网站(在这种情况下是谷歌)稍后将调用相同的函数,但使用常规(未更改的)地理位置。很高兴听到永久更改传感器以影响未来地理位置请求的解决方案。


0

这可以使用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");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接