天气数据的爬行Python代码
时间: 2024-10-08 08:08:23 浏览: 24
用Python爬行
在Python中,我们可以使用`requests`库来爬取公开的天气API数据。这里以OpenWeatherMap (OWM) API为例,它提供了一个简单的RESTful API。下面是一个基本的示例代码,假设你已经注册了OWM API并获取了API key:
```python
import requests
import json
def get_weather_data(city_name, api_key):
base_url = "http://api.openweathermap.org/data/2.5/weather"
params = {
"q": city_name,
"appid": api_key,
"units": "metric" # 或者 "imperial" 根据需求选择单位
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status() # 检查是否成功,如果状态码不是200则抛出异常
data = response.json()
main_data = data['main']
weather_data = data['weather'][0]
temperature = main_data['temp']
humidity = main_data['humidity']
description = weather_data['description']
return {
'temperature': temperature,
'humidity': humidity,
'description': description
}
except requests.exceptions.RequestException as e:
print(f"Error fetching weather data: {e}")
return None
city = "北京"
api_key = "your_openweathermap_api_key"
weather_data = get_weather_data(city, api_key)
if weather_data is not None:
print(f"Weather in {city}:")
for key, value in weather_data.items():
print(f"{key.capitalize()}: {value}")
```
注意替换`your_openweathermap_api_key`为你实际的API密钥。上述代码仅用于演示,实际使用时应考虑更完善的错误处理和API速率限制。
阅读全文