帮我用python写一个爬取城市天气信息的代码
时间: 2024-06-10 13:07:57 浏览: 86
爬取指定城市气象数据python代码
好的,以下是Python的代码示例,使用BeautifulSoup和requests库:
```
import requests
from bs4 import BeautifulSoup
city = input("请输入要查询的城市名:")
def get_weather(city):
url = "https://tianqi.moji.com/weather/china/" + city
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
temperature = soup.find("div", attrs={"class": "wea_weather clearfix"}).em.getText()
weather = soup.find("div", attrs={"class": "wea_weather clearfix"}).b.getText()
wind_direction = soup.find("div", attrs={"class": "wea_about clearfix"}).em.getText()
wind_speed = soup.find("div", attrs={"class": "wea_about clearfix"}).i.getText()
return temperature, weather, wind_direction, wind_speed
temperature, weather, wind_direction, wind_speed = get_weather(city)
print(f"{city}的天气信息:\n温度:{temperature}\n天气:{weather}\n风向:{wind_direction}\n风速:{wind_speed}")
```
希望以上代码能够帮到您,如果还有其他问题,可以随时再问我哦。
阅读全文