我想使用Python脚本获得准确的位置。我已经尝试了基于IP位置的不同服务,它根本不起作用(总是远离我的实际位置)。
我注意到HTML5地理定位工具在Firefox和谷歌浏览器上非常准确,因此我决定使用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.朋友
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()
你知道怎么解决这个问题吗?
谢谢!
您可以使用基于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"