如何在 Selenium Chromedriver 中设置时区?

新手上路,请多包涵

我不知道如何在使用 Chromedriver 时设置时区。是否有一些 ChromeOptions 参数或其他东西?

问题是,当我访问某些站点(例如 https://whoer.net )时,它显示的系统时间等于 Windows 上设置的时间。我希望能够以某种方式更改 Chromedriver 的时区以执行时区相关测试。

我试图设置一些 chrome 选项:

 Map<String, Object> chromeOptions = new HashMap<String, Object>();
chromeOptions.put("args", Arrays.asList("--disable-system-timezone-automatic-detection", "--local-timezone"));
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

它不起作用。

尝试使用 Javascript 做一些奇怪的事情:

 ((JavascriptExecutor) driver).executeScript("Date.prototype.getTime = function() { return 1 };");


它也没有帮助。

编辑:

发现这个 https://sqa.stackexchange.com/questions/8838/faking-system-time-date-with-selenium-webdriver

尝试使用从 TimeShift.js 复制的代码在页面上执行 javascript,如下所示:

 ((JavascriptExecutor) driver).executeScript("/*code from TimeShift.js here*/ TimeShift.setTimezoneOffset(-60);");

https://whoer.net 的系统时间没有改变。我究竟做错了什么?

原文由 Helen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
1 个回答

您可以使用 Chrome DevTools Protocol 来完成,这里是 python 代码:

 driver = webdriver.Chrome()
tz_params = {'timezoneId': 'America/New_York'}
driver.execute_cdp_cmd('Emulation.setTimezoneOverride', tz_params)

原文由 garrythehotdog 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题