You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3 BeautifulSoup+Requests提取经纬度及精度问题求助

问题排查与解决方案

首先得跟你说清楚核心问题:这个网站的地理坐标是通过JavaScript动态生成的,而requests只能抓取页面的静态HTML源码——那些带id="latitude"、id="longitude"的<td>元素,是浏览器执行JS后才渲染出来的,所以你的BeautifulSoup根本找不到这些动态生成的元素,自然返回空列表。

下面给你两种可行的解决办法,按需选择:

方法一:直接调用网站的API接口(推荐)

我研究了这个网站的网络请求,发现它会调用一个后台API来获取坐标数据,我们可以跳过HTML解析,直接请求这个接口拿结构化数据:

import requests

def track_the_location():
    # 网站用来获取坐标的API接口
    api_url = "https://mycurrentlocation.net/api/location"
    response = requests.get(api_url)
    data = response.json()
    
    latitude = data.get('latitude')
    longitude = data.get('longitude')
    accuracy = data.get('accuracy')
    
    print(f"纬度: {latitude}")
    print(f"经度: {longitude}")
    print(f"精度: {accuracy} 米")

track_the_location()

这种方法效率更高,不用处理复杂的HTML结构,而且数据是结构化的JSON,后续处理也更方便,还不容易受页面改版的影响。

方法二:用Selenium模拟浏览器加载动态内容

如果你一定要通过解析页面元素来获取数据,可以用Selenium模拟浏览器运行,等JS渲染完成后再提取元素:

首先需要安装依赖(以及对应浏览器的驱动,比如ChromeDriver):

pip install selenium

然后编写代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def track_the_location():
    site = "https://mycurrentlocation.net/"
    # 初始化Chrome浏览器驱动(需确保ChromeDriver在系统PATH中)
    driver = webdriver.Chrome()
    driver.get(site)
    
    try:
        # 等待目标元素加载完成,最多等待10秒
        latitude = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "latitude"))
        ).text
        longitude = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "longitude"))
        ).text
        accuracy = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "accuracy"))
        ).text
        
        print(f"纬度: {latitude}")
        print(f"经度: {longitude}")
        print(f"精度: {accuracy}")
    finally:
        # 不管结果如何,最后关闭浏览器
        driver.quit()

track_the_location()

额外小提醒

你原来的代码还有个小细节问题:find_all返回的是元素列表,就算找到元素也需要通过索引(比如latitude[0].text)才能拿到文本内容,但这不是核心问题——毕竟动态加载的元素在静态HTML里根本不存在,所以就算修正这个细节,也拿不到数据。

内容的提问来源于stack exchange,提问作者dimitrissin8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:25:13