如何从yr.no提取Jordalen-Nåsen区域雪深数据至DataFrame
提取Jordalen - Nåsen区域雪深数据并存储到Pandas DataFrame
你的代码目前能抓取所有雪深数值,但没关联对应区域。要定位到Jordalen - Nåsen的雪深,需要先找到包含区域名称和雪深值的关联DOM容器,再筛选目标区域。
解决步骤
- 定位页面中每个区域的雪深条目容器(页面里每个区域的名称和雪深都包裹在同一个父元素内,比如
div.snow-depth__item) - 遍历所有条目容器,匹配目标区域名称
- 提取对应雪深值,存入Pandas DataFrame
完整代码
import pandas as pd import requests from bs4 import BeautifulSoup # 发送请求获取页面 url = 'https://www.yr.no/nb/sn%C3%B8dybder/NO-46/Norge/Vestland' r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') # 找到所有区域的雪深条目容器 snow_items = soup.find_all("div", {"class": "snow-depth__item"}) # 初始化存储数据的列表 snow_data = [] # 遍历条目,筛选目标区域 target_area = "Jordalen - Nåsen" for item in snow_items: # 提取区域名称 area_name = item.find("span", {"class": "snow-depth__location"}).text.strip() # 提取雪深数值 depth_value = item.find("span", {"class": "snow-depth__value"}).text.strip() # 匹配目标区域 if area_name == target_area: snow_data.append({"区域名称": area_name, "雪深(cm)": depth_value}) # 转换为DataFrame df = pd.DataFrame(snow_data) print(df)
说明
- 页面中每个区域的名称在
span.snow-depth__location标签内,雪深值在同容器下的span.snow-depth__value内,通过父容器关联两者 - 如果目标区域存在,会输出包含区域名称和雪深的DataFrame;如果不存在,DataFrame为空,可根据需求添加异常处理逻辑
内容的提问来源于stack exchange,提问作者slabbe
相关产品推荐
相关产品推荐

