我想使用 Python 脚本获取我的准确位置。 我已经尝试过基于 IP 位置的不同服务,但根本不起作用(总是离我的实际位置很远)。
我注意到 HTML5 地理定位工具在 Firefox 和 Google Chrome 上非常准确,所以我决定使用 selenium 模块启动网络浏览器并从中获取我的位置。
虽然我面临两个问题:首先,我不能强制 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>
测试.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()
你知道怎么解决吗?
谢谢!
最佳答案
我发现 Geoclue 非常准确,这可能已经在您的系统上了。只需安装 gir1.2-geoclue-2.0 包,然后:
from gi.repository import Geoclue
clue = Geoclue.Simple.new_sync('something',Geoclue.AccuracyLevel.EXACT,None)
location = clue.get_location()
print(location.get_property('latitude'), location.get_property('longitude'))
有关详细信息,请参阅我的 blog post .
关于python - 我可以使用 HTML5 定位工具在 Python 中获得准确的地理定位吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45630606/