from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import json
import time
s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)
driver.get('https://www.google.com')
string = '''
function getLocation(callback) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var myjson = {"latitude":position.coords.latitude, "longitude":position.coords.longitude};
console.log(position);
console.log(position.coords.latitude);
console.log(position.coords.longitude);
var stringJson = JSON.stringify(myjson);
callback(stringJson);
});
} else {
console.log("Geolocation is not supported by this browser.");
}
}
getLocation(function(callback) {
console.log(callback);
const para = document.createElement("p");
para.innerHTML = callback;
para.id = "location";
document.body.appendChild(para);
});'''.replace('\n', '').replace('\t', '')
# repeat this code
driver.execute_script(string)
time.sleep(2)
res = driver.find_element(By.ID, "location")
loc = res.text
locDict = json.loads(loc)
print("latitude: %f, longitude: %f" % (locDict["latitude"], locDict["longitude"]))
我使用这个 python 代码来获取位置。我认为你必须安装 chrome 才能运行它:v
由于我不是很懂,这只是我的猜测,所以如果我错了,请纠正我:
首先,我使用 webdriver。我打算打开 Chrome 浏览器并使用网络浏览器中的 javascript 函数来获取我的位置。
运行此代码时,Chrome 浏览器将打开。不要关闭它,否则代码将不起作用
那么,变量字符串就是一堆javascript代码。此代码将在网络浏览器上执行,地址为www.google.com,使用driver.execute_script(string)
该javascript代码的目的是使用navigator.geolocation.getCurrentPosition()获取位置g,然后将其写入JSON字符串中。然后,我创建了一个 id="location" 的 <p> 元素,但其中包含 JSON 字符串,然后附加到 Web。在代码运行完成后,您会在网站底部看到一个 json 字符串
之后,我需要找到
在我之前插入的网络中具有 id="location" 的元素driver.find_element(By.ID, "location"),获取该 JSON 字符串,对其进行解析并获取纬度和经度的值
你可能会问我为什么要创建一个<p> 元素并将其放到网络上。嗯,执行json字符串的时候,找不到从position.coords.latitude和position.coords.longitude返回经纬度值的方法,所以决定写在网上,以后再找。