2017-08-11 35 views
0

我想使用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() 

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

谢谢!

+0

也许无头的Chrome可以帮到你。 https://developers.google.com/web/updates/2017/04/headless-chrome –

+0

尽管现在我想到了,除非您的GPS已连接到您的计算机,Firefox和Chrome也只能使用您的IP。也许他们的服务更好。 –

+0

我会研究它,谢谢! – LeChocdesGitans

回答

0

计算机等的位置(没有gps或glonas)是基于IP的。 可以使用一些网站

import requests 
import json 

send_url = 'http://freegeoip.net/json' 
r = requests.get(send_url).text 
lat = j['latitude'] 
lon = j['longitude'] 
+0

我已经尝试过这种服务,但它不够准确,这就是为什么我想要使用Firefox或Chrome位置服务,这种服务效果更好。不过谢谢! – LeChocdesGitans

+0

您认为您的浏览器给您的位置如何?它使用这种服务。 – Rahul

+0

是的,我得到了这个,但Firefox或Chrome用来定位的服务比我用过的任何服务都高效得多。你知道一种直接使用它的方式,而不是打开浏览器吗? – LeChocdesGitans

1

做在Python本身你可以得到的地理位置与基于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"