我可以使用 HTML5 定位工具在 Python 中获得准确的地理位置吗?

LeC*_*ans 5 html python position geolocation

我想使用 Python 脚本获得准确的位置。我尝试过基于 IP 位置的不同服务,但根本不起作用(总是离我的实际位置很远)。

我注意到 HTML5 地理定位工具在 Firefox 和 Google Chrome 上相当准确,因此我决定使用 selenium 模块启动网络浏览器并从中获取我的位置。

虽然我面临两个问题:首先,我无法强制 Firefox 或 Chrome 允许本地网页上的位置服务。其次,我不知道如何获取获取坐标的 JavaScript 函数的结果。

这是我到目前为止所做的:

地理.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>
Run Code Online (Sandbox Code Playgroud)

测试.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()
Run Code Online (Sandbox Code Playgroud)

你知道如何解决这个问题吗?

谢谢!

Jis*_*P K 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"
Run Code Online (Sandbox Code Playgroud)