You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.1 KiB

import requests
from bs4 import BeautifulSoup
async def get_weather(city_name):
url = "https://www.weather.com.cn/textFC/db.shtml"
response = requests.get(url)
html_content = response.content
soup = BeautifulSoup(html_content, 'html.parser')
# 获取日期
day_tabs = soup.find('ul', class_='day_tabs')
days = [day.text.strip() for day in day_tabs.find_all('li')]
# 获取天气信息
weather_data = []
tables = soup.find_all('table', width="100%") # 找到所有天气表格
day = 0
for table in tables:
rows = table.find_all('tr')[2:] # 跳过前两行表头
for row in rows:
cols = row.find_all('td')
if len(cols) >= 7: # 确保是数据行
city = cols[1].text.strip()
if city != city_name:
continue
day_weather = cols[2].text.strip()
day_wind = cols[3].text.strip()
day_temp = cols[4].text.strip()
night_weather = cols[5].text.strip()
night_wind = cols[6].text.strip()
night_temp = cols[7].text.strip()
d = days[day]
day = day + 1
weather_data.append({
'day': d,
'city': city,
'day_weather': day_weather,
'day_wind': day_wind,
'day_temp': day_temp,
'night_weather': night_weather,
'night_wind': night_wind,
'night_temp': night_temp
})
# 打印结果
for data in weather_data:
print(f"日期: {data['day']}")
print(f"城市: {data['city']}")
print(f"白天天气: {data['day_weather']}, 风向风力: {data['day_wind']}, 最高气温: {data['day_temp']}")
print(f"夜间天气: {data['night_weather']}, 风向风力: {data['night_wind']}, 最低气温: {data['night_temp']}")
print('-' * 40)
return weather_data