在Chrome Headless中设置自定义位置坐标是否可能? 我在 Devtools协议 API中找不到它。 是否有可用的解决方法?
我在谷歌上搜索了许多方法,一个一个尝试后发现几乎所有方法都已经过时了。然后我找到了一种解决方案,使用Chrome开发者工具协议来实现。
下面是一个小例子代码,它使用最常见的工具Selenium来执行Chrome开发者工具协议命令。
import time
from selenium.webdriver import Chrome, ChromeOptions
options = ChromeOptions()
options.add_argument("--headless")
driver = Chrome(options=options)
driver.execute_cdp_cmd(
"Browser.grantPermissions",
{
"origin": "https://www.openstreetmap.org/",
"permissions": ["geolocation"]
},
)
driver.execute_cdp_cmd(
"Emulation.setGeolocationOverride",
{
"latitude": 35.689487,
"longitude": 139.691706,
"accuracy": 100,
},
)
driver.get("https://www.openstreetmap.org/")
driver.find_element_by_xpath("//span[@class='icon geolocate']").click()
time.sleep(3) # wait for the page full loaded
driver.get_screenshot_as_file("screenshot.png")
https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setGeolocationOverride
并且
https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-clearGeolocationOverride
... 然后您需要考虑如何确保在用户配置文件中设置了正确的位置共享设置(chrome://settings/content/location - 由于通过阴影DOM显示,因此很难访问,因此使用预配置的用户配置文件可能更容易--user-data-dir
)。
补充说明:上述方法在使用--headless
时似乎不起作用。为解决这个问题,我使用了https://chromedevtools.github.io/devtools-protocol/tot/Page#method-addScriptToEvaluateOnNewDocument和以下片段:
navigator.geolocation.getCurrentPosition = function(success, failure) {
success({
coords: {latitude: <your_lat_float>, longitude: <your_lng_float>},
timestamp: Date.now(),
});
}