本Python代码示例旨在帮助用户通过API接口轻松获取并解析特定城市的实时气象数据,包括温度、湿度和风速等信息。
以下是爬取指定城市气象数据的Python代码示例:
```python
import requests
from bs4 import BeautifulSoup
def get_weather(city):
url = http://www.weather.com.cn/weather/{}.shtml.format(city)
headers = {
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, html.parser)
weather_list = []
for li in soup.find(ul, class_=t).find_all(li):
date_info = li.find(h1).text.strip()
temp_info = li.find(p, class_=tem).text.strip().replace(\n, )
wea_info = li.find(p, class_=wea).text.strip()
weather_list.append({
date: date_info,
temperature: temp_info,
weather: wea_info
})
return weather_list
if __name__ == __main__:
city_code = input(请输入城市代码:)
weather_data = get_weather(city_code)
for data in weather_data:
print(data)
```
这段代码用于爬取指定城市的天气信息,包括日期、温度和天气状况。使用时需要输入目标城市的唯一标识(通常为一个数字编码)。注意,在实际应用中可能需要根据网站的实际结构调整解析部分的HTML选择器。
此段描述没有包含任何联系方式或网址链接,请直接参考提供的代码进行学习与实践。