自动从网站收集天气数据并写入 CSV 文件

209 阅读2分钟

给定一个网站 www.wunderground.com/global/stat… Python 脚本,每小时自动从该网站收集天气数据,包括温度和当前天气状况,并将数据存储在一个 CSV 文件中,CSV 文件的标题包括日期时间、当前天气状况和温度。脚本需要连续运行 5 天。

huake_00152_.jpg

2. 解决方案

2.1 使用 Python 自带库请求数据

import requests
import csv
import time
from datetime import datetime

# 设置要请求的网站 URL
url = "http://www.wunderground.com/global/stations/54511.html"

# 设置请求头,模拟浏览器行为
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36"
}

# 设置 CSV 文件的标题
headers = ["Datetime", "Current Condition", "Temperature"]

# 打开 CSV 文件,准备写入数据
with open("weather_data.csv", "w", newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(headers)

# 设置循环次数,5 天等于 120 次
for i in range(120):
    # 获取当前时间戳
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # 请求网站并获取 HTML 内容
    response = requests.get(url, headers=headers)

    # 解析 HTML 内容,提取天气数据
    html = response.text
    temperature = html.split('<span class="wu-value wu-temperature">')[1].split('</span>')[0]
    condition = html.split('<div class="condition-icon current-observation">')[1].split('</div>')[0]

    # 将数据写入 CSV 文件
    csvwriter.writerow([timestamp, condition, temperature])

    # 每小时运行一次
    time.sleep(3600)

2.2 使用第三方库 Beautiful Soup 解析 HTML

import requests
import csv
import time
from datetime import datetime
from bs4 import BeautifulSoup

# 设置要请求的网站 URL
url = "http://www.wunderground.com/global/stations/54511.html"

# 设置请求头,模拟浏览器行为
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36"
}

# 设置 CSV 文件的标题
headers = ["Datetime", "Current Condition", "Temperature"]

# 打开 CSV 文件,准备写入数据
with open("weather_data.csv", "w", newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(headers)

# 设置循环次数,5 天等于 120 次
for i in range(120):
    # 获取当前时间戳
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # 请求网站并获取 HTML 内容
    response = requests.get(url, headers=headers)

    # 解析 HTML 内容,提取天气数据
    soup = BeautifulSoup(response.text, 'html.parser')
    temperature = soup.find('span', class_='wu-value wu-temperature').text
    condition = soup.find('div', class_='condition-icon current-observation').text

    # 将数据写入 CSV 文件
    csvwriter.writerow([timestamp, condition, temperature])

    # 每小时运行一次
    time.sleep(3600)

上述代码中,我们使用了 requests 库来发送 HTTP 请求,使用了 csv 库来写入 CSV 文件,使用了 time 库来设置循环间隔,使用了 datetime 库来获取当前时间戳,使用了 Beautiful Soup 库来解析 HTML 内容。