使用 Python 爬取空气质量数据(以哈尔滨为例)(学习自用)

在数据科学和分析领域,网络爬虫是一项重要的技能。本文将介绍如何使用 Python 爬取哈尔滨市的空气质量数据,并将其保存为 CSV 文件,以便进一步分析。

所需工具

我们将使用以下 Python 库:

  • requests:用于发送 HTTP 请求。
  • BeautifulSoup:用于解析 HTML 和 XML 文档。
  • pandas:用于数据操作和分析。
  • chardet:用于检测网页的编码格式。

确保你已经安装了这些库。如果没有安装,可以使用以下命令进行安装:

pip install requests beautifulsoup4 pandas chardet

爬取后的数据如下表所示。

DateQuality LevelAQI IndexRankingPM2.5PM10SO2NO2COO3
2023/2/1中度污染15531011713524481.0949
2023/2/251147344816280.6749
2023/2/3轻度污染1043087810326501.0435
2023/2/4轻度污染14031410612921441.144
2023/2/597205719821300.7156
2023/2/6重度污染20931716518420501.0744
2023/2/796227709420450.939
2023/2/883213608420440.9635
2023/2/973248517520440.9740
2023/2/1071212515814290.7557
2023/2/11轻度污染110292839312340.9657
2023/2/1288289657519370.8164
2023/2/13轻度污染114333841021646149
2023/2/1440178273817250.5656
2023/2/1571260516919400.8643

爬虫代码

下面是完整的爬虫代码,用于从 http://www.tianqihoubao.com/aqi/haerbin- 网站上抓取2023年2月到2023年3月的空气质量数据。

import requests
from bs4 import BeautifulSoup
import pandas as pd
import chardet

# Define the base URL and the range of months to scrape
base_url = 'http://www.tianqihoubao.com/aqi/haerbin-'
months = pd.date_range('2023-02', '2023-03', freq='MS').strftime("%Y%m").tolist()

# Initialize empty lists to store the data
dates = []
quality_levels = []
aqi_indices = []
rankings = []
pm25_values = []
pm10_values = []
so2_values = []
no2_values = []
co_values = []
o3_values = []

# Function to extract data from a given URL
def extract_data(url):
    retries = 3  # Number of retries
    for attempt in range(retries):
        try:
            response = requests.get(url)
            # Detect encoding if not set to 'utf-8'
            if response.encoding == 'ISO-8859-1':
                detected_encoding = chardet.detect(response.content)['encoding']
                response.encoding = detected_encoding if detected_encoding else 'utf-8'
            soup = BeautifulSoup(response.text, 'html.parser')
            table = soup.find('table', {'class': 'b'})
            if table:
                for row in table.find_all('tr')[1:]:
                    columns = row.find_all('td')
                    dates.append(columns[0].text.strip())
                    quality_levels.append(columns[1].text.strip())
                    aqi_indices.append(columns[2].text.strip())
                    rankings.append(columns[3].text.strip())
                    pm25_values.append(columns[4].text.strip())
                    pm10_values.append(columns[5].text.strip())
                    so2_values.append(columns[6].text.strip())
                    no2_values.append(columns[7].text.strip())
                    co_values.append(columns[8].text.strip())
                    o3_values.append(columns[9].text.strip())
            break  # Exit the retry loop if the request is successful
        except (requests.exceptions.ConnectionError, requests.exceptions.ChunkedEncodingError) as e:
            print(f"Error occurred: {e}. Retrying {attempt + 1}/{retries}...")
            time.sleep(5)  # Wait for 5 seconds before retrying
        except Exception as e:
            print(f"An unexpected error occurred: {e}")
            break

# Iterate through each month and extract data
for month in months:
    url = base_url + month + '.html'
    extract_data(url)

# Create a DataFrame to store the data
data = {
    'Date': dates,
    'Quality Level': quality_levels,
    'AQI Index': aqi_indices,
    'Ranking': rankings,
    'PM2.5': pm25_values,
    'PM10': pm10_values,
    'SO2': so2_values,
    'NO2': no2_values,
    'CO': co_values,
    'O3': o3_values
}
df = pd.DataFrame(data)

# Display the DataFrame
print(df)

# Save the DataFrame to a CSV file with utf-8 encoding
df.to_csv('harbin_air.csv', index=False, encoding='utf-8-sig')

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值