You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用BeautifulSoup爬取前切换下拉菜单获取逐时天气数据

解决timeanddate.com整月天气数据爬取的日期切换问题

要获取2022年1月所有日期的逐时天气数据,核心是模拟日期切换的请求逻辑:该网站通过POST请求传递日期参数hd(格式为YYYYMMDD)来加载对应日期的数据。以下是修改后的完整代码:

from bs4 import BeautifulSoup
import requests
import pandas as pd
from datetime import datetime, timedelta

# 基础URL和请求头(添加User-Agent避免反爬)
base_url = 'https://www.timeanddate.com/weather/saudi-arabia/riyadh/historic'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

# 初始化DataFrame
df = pd.DataFrame(columns=['Date', 'Time', 'Temp', 'Weather', 'Wind', 'Humidity'])

# 设置起始和结束日期(2022年1月1日到1月31日)
start_date = datetime(2022, 1, 1)
end_date = datetime(2022, 1, 31)

current_date = start_date
while current_date <= end_date:
    # 构造日期参数hd(格式YYYYMMDD)
    hd_param = current_date.strftime('%Y%m%d')
    # 构造表单数据
    form_data = {
        'month': '1',
        'year': '2022',
        'hd': hd_param
    }
    
    # 发送POST请求获取对应日期的页面
    response = requests.post(base_url, data=form_data, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 解析表格数据
    table = soup.find('table', id='wt-his')
    if not table:
        print(f"未找到{current_date.date()}的天气数据")
        current_date += timedelta(days=1)
        continue
    
    # 获取日期文本
    date_text = table.tbody.find_all('tr')[0].find('th').text.strip()[5:]
    
    # 遍历表格行提取数据
    for row in table.tbody.find_all('tr'):
        time_th = row.find('th')
        columns = row.find_all('td')
        if time_th and columns:
            time = time_th.text.strip()[:5]
            temp = columns[1].text.strip()
            weather = columns[2].text.strip()
            wind = columns[3].text.strip()
            humidity = columns[5].text.strip()
            
            # 添加到DataFrame(用pd.concat替代append,append已弃用)
            new_row = pd.DataFrame({
                'Date': [date_text],
                'Time': [time],
                'Temp': [temp],
                'Weather': [weather],
                'Wind': [wind],
                'Humidity': [humidity]
            })
            df = pd.concat([df, new_row], ignore_index=True)
    
    print(f"已完成{current_date.date()}的数据爬取")
    current_date += timedelta(days=1)

# 保存数据到CSV
df.to_csv('riyadh_202201_hourly_weather.csv', index=False)
print("所有数据爬取完成,已保存到riyadh_202201_hourly_weather.csv")

关键说明:

  • 请求方式:改用POST请求传递hd参数,模拟页面日期切换的行为,而非直接访问原GET URL。
  • 反爬处理:添加User-Agent请求头,避免被网站识别为爬虫而拒绝访问。
  • 数据合并:使用pd.concat替代已弃用的df.append,保证代码兼容性。
  • 日期遍历:通过datetime模块循环生成1月的所有日期,自动构造hd参数。

内容的提问来源于stack exchange,提问作者Hkord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:00:27