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

使用Python+Beautiful Soup实现定时天气爬虫语音播报时数据不更新求助

问题根因
  • 核心错误:requests.get()传参错误,第二个位置参数对应请求查询参数params,你把headers字典放到了这个位置,导致自定义请求头完全没有生效,服务器要么返回了缓存的静态内容,要么识别为爬虫请求直接返回固定响应。
  • 不规范操作:所有import语句、pyttsx3语音引擎初始化都放在循环内部,每次循环重复执行无意义的加载逻辑,既拉低运行效率也可能引发资源占用异常。
  • 选择器兼容问题:你选取天气描述所用的类名是按天预报的专属属性,部分场景下可能匹配到非实时的预报内容,建议确认实时数据对应的元素选择器是否准确。
修正后可运行代码
# 所有导入操作统一放在代码开头
import requests
from bs4 import BeautifulSoup
import pyttsx3
import time

# 全局初始化只执行一次
text_speech = pyttsx3.init()
headers = {
    'User-Agent': "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Mobile Safari/537.36 Edg/94.0.992.31",
    'Cache-Control': 'no-cache' # 新增禁用缓存头,强制获取最新内容
}
# 替换为对应城市的天气页面地址
url = "https://www.bbc.com/weather/your-city-id"
n = 10 # 可自行修改循环执行次数

for i in range(n):
    t = time.localtime()
    current_hr = time.strftime("%H:%M", t)
    # 正确传递headers参数
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text,"html.parser")
    
    # 提取页面信息
    location = soup.find('h1', attrs={"id": "wr-location-name-id"}).text
    temp_c = soup.find('span', attrs={"class": "wr-value--temperature--c"}).text
    weather_desc = soup.find('div', attrs={"class": "wr-day__weather-type-description wr-js-day-content-weather-type-description wr-day__content__weather-type-description--opaque"}).text

    # 语音播报
    text_speech.say(current_hr)
    text_speech.say(location)
    text_speech.say(f"现在的温度是{temp_c}")
    text_speech.say(weather_desc)
    text_speech.runAndWait()
    
    print(current_hr, location, temp_c, weather_desc)
    time.sleep(600)
优化建议
  • 可添加try-except异常捕获逻辑,处理网络波动、元素匹配失败等异常场景,避免程序直接崩溃
  • 如果目标页面存在动态渲染的内容,可替换为requests-html或者selenium工具获取动态加载的实时数据
  • 可配置日志记录每次爬取的结果,方便后续排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:54:05