Python爬取天气温湿度

引言

天气是我们日常生活中非常重要的信息之一,而温度和湿度是天气的两个关键参数。通过爬取相关的天气网站,我们可以获取到实时的温湿度数据,以便更好地了解当前的天气状况。

本文将介绍如何使用Python编写一个简单的爬虫程序,来获取天气的温度和湿度数据,并对数据进行处理和展示。

准备工作

在开始之前,我们需要先安装一些必要的Python库。其中,最主要的是requestsbeautifulsoup4,用于发送HTTP请求和解析HTML。

可以通过以下命令使用pip安装这两个库:

pip install requests beautifulsoup4

网站选择

首先,我们需要选择一个天气网站来进行爬取。在本文中,我们将使用[中国天气网](

该网站提供了全国各个城市的天气信息,包括温度、湿度、风力等。

爬取天气数据

我们将使用Python的requests库发送HTTP请求,然后使用beautifulsoup4库解析HTML,并提取出温湿度数据。

以下是一个简单的示例代码:

import requests
from bs4 import BeautifulSoup

def get_weather(city_code):
    url = f"
    response = requests.get(url)
    response.encoding = "utf-8"
    soup = BeautifulSoup(response.text, "html.parser")
    
    temperature = soup.select_one(".tem span").get_text()
    humidity = soup.select_one(".shidu .hide").get_text()
    
    return temperature, humidity

city_code = "101280101"  # 武汉的城市代码
temperature, humidity = get_weather(city_code)
print(f"当前温度:{temperature}℃")
print(f"当前湿度:{humidity}")

上述代码中,get_weather函数接受一个城市代码作为参数,然后构建相应的URL并发送HTTP请求。通过beautifulsoup4库解析HTML,我们可以方便地提取出温度和湿度数据。

数据处理和展示

获取到温湿度数据后,我们可以对其进行进一步的处理和展示。这里,我们使用matplotlib库来绘制折线图,展示过去24小时的温湿度变化。

以下是一个简单的示例代码:

import matplotlib.pyplot as plt
import numpy as np

def plot_weather(temperatures, humidities):
    hours = np.arange(24)
    
    plt.figure(figsize=(8, 6))
    plt.plot(hours, temperatures, label="Temperature", marker="o")
    plt.plot(hours, humidities, label="Humidity", marker="o")
    
    plt.xlabel("Hour")
    plt.ylabel("Value")
    plt.title("Weather in the Past 24 Hours")
    plt.xticks(hours)
    plt.legend()
    plt.grid(True)
    plt.show()

temperatures = [25, 24, 23, 22, 22, 23, 24, 25, 26, 28, 30, 31, 31, 30, 29, 28, 27, 26, 25, 24, 24, 23, 22, 21]
humidities = [70, 75, 80, 82, 85, 88, 90, 92, 92, 90, 88, 85, 82, 80, 80, 82, 85, 88, 90, 92, 92, 90, 88, 85]

plot_weather(temperatures, humidities)

上述代码中,plot_weather函数接受两个列表作为温度和湿度数据,然后使用matplotlib库绘制折线图,展示过去24小时的温湿度变化。

总结

通过本文的介绍,我们学习了如何使用Python爬取天气的温湿度数据,并对数据进行处理和展示。这是一个简单的示例,可以根据实际需求进行扩展和优化。

希望本文对你了解Python爬取天气温湿度有所帮助!