我想使用Python脚本获得准确的位置。 我已经尝试了基于IP位置的不同服务,根本没有工作(总是离我的实际位置很远)。我可以使用HTML5定位工具在Python中获得准确的地理位置吗?
我注意到Google Chrome浏览器中的HTML5地理定位工具非常准确,所以我决定使用硒模块启动Web浏览器并从中获取我的位置。
尽管我面临两个问题:首先,我无法强制Firefox或Chrome在本地网页上允许定位服务。其次,我不知道如何获取我获得坐标的javascript函数的结果。
这是我到目前为止已经完成:
geo.html
<html>
<head>
<title>Test</title>
<p id="demo"></p>
<script type="text/javascript">
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(showPosition);
} else {
return "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</head>
<body>
<p>The element below will receive content</p>
<div id="div" />
<script type="text/javascript">getLocation()</script>
</body>
</html>
test.py
from selenium import webdriver
from pyvirtualdisplay import Display
try:
display = Display(visible=1, size=(800, 600))
display.start()
browser = webdriver.Firefox()
browser.get('file:///path/to/geo.html')
res = browser.execute_script("getLocation()")
print(res)
except KeyboardInterrupt:
browser.quit()
display.stop()
你知道如何解决这个问题?
谢谢!
也许无头的Chrome可以帮到你。 https://developers.google.com/web/updates/2017/04/headless-chrome –
尽管现在我想到了,除非您的GPS已连接到您的计算机,Firefox和Chrome也只能使用您的IP。也许他们的服务更好。 –
我会研究它,谢谢! – LeChocdesGitans