Python爬取天气数据:抓取成都市未来7天天气预报
以下是更新后的代码:
import requests
from bs4 import BeautifulSoup
# 发送HTTP请求,获取网页内容
url = "http://www.weather.com.cn/weather/101270101.shtml"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
# 解析网页内容,提取天气数据
weather_data = []
forecast_div = soup.find(id="7d")
ul = forecast_div.find("ul")
lis = ul.find_all("li")
for li in lis:
date = li.find(class_="time").text.strip()
weather = li.find(class_="wea").text.strip()
temperature = li.find(class_="tem").text.strip().replace("℃", "")
wind = li.find(class_="wind").text.strip()
dress_index = li.find(class_="li").text.strip()
weather_data.append((date, weather, temperature, wind, dress_index))
# 在控制台打印天气数据
for data in weather_data:
print("日期:", data[0])
print("天气:", data[1])
print("温度:", data[2])
print("风力:", data[3])
print("穿衣指数:", data[4])
print("-----------------")
请将以上代码复制到你的Python环境中运行,即可在控制台中显示成都市未来七天的天气数据。如果还有其他问题,请随时向我提问。
原文地址: https://www.cveoy.top/t/topic/NVQ 著作权归作者所有。请勿转载和采集!