使用HTML5位置工具,我能在Python中获取准确的地理位置吗?

5
我想使用Python脚本获取我的准确位置。我已经尝试了基于IP定位的不同服务,但都没有成功(总是离我的实际位置很远)。
我注意到HTML5地理定位工具在Firefox和Google Chrome上非常准确,所以我决定使用selenium模块启动一个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 - Björn Tantau
虽然我现在想想,除非你的计算机连接了GPS,否则Firefox和Chrome也只能使用你的IP。也许他们的服务只是更好。 - Björn Tantau
我会调查一下,谢谢! - LeChocdesGitans
2个回答

1

你可以使用基于IP的方式获取地理位置。

import requests
import json

response_data = requests.get('https://www.iplocation.net/go/ipinfo').text
try:
   response_json_data = json.loads(response_data)
   location = response_json_data["loc"].split(",")
   print "Latitude: %s" % location[0]
   print "Longitude: %s" % location[1]
except ValueError:
   print "Exception happened while loading data"

1
此 API 已不再提供。 - Hugo

1

我发现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'))

更多细节请参见我的博客文章

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