Python爬取微博热搜并实时发送到邮箱:零基础实现指南

简介: 本文介绍如何用Python实现微博热搜自动抓取与邮件推送,通过requests、BeautifulSoup和smtplib等库,50行代码即可完成定时监控,解决数据获取、解析与发送难题,提升信息获取效率。

​免费编程软件「python+pycharm」
链接:https://pan.quark.cn/s/48a86be2fdc0

一、项目背景与核心目标
微博热搜是大众关注的实时信息窗口,但手动刷新查看效率低下。通过Python自动化技术,我们可以实现热搜数据的定时抓取,并通过邮件实时推送最新内容。本文将分步骤讲解如何用50行代码完成这一功能,重点解决网络请求、数据解析和邮件发送三大核心问题。
探秘代理IP并发连接数限制的那点事 (97).png

二、技术准备清单
Python环境:建议3.8+版本
核心库:
requests:处理HTTP请求
BeautifulSoup:解析HTML内容
smtplib:发送邮件
schedule:定时任务管理
邮箱配置:需开通SMTP服务(以QQ邮箱为例)
三、代码实现四步走

  1. 破解网页请求
    微博热搜页面(https://s.weibo.com/top/summary)采用动态加载技术,直接请求HTML会缺失关键数据。解决方案:

import requests
from bs4 import BeautifulSoup

def get_weibo_hot():
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
url = 'https://s.weibo.com/top/summary'
try:
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

    # 解析热搜条目(具体CSS选择器需根据实际页面调整)
    hot_list = soup.select('table.td-02 a')[:10]  # 取前10条
    return [item.text for item in hot_list]
except Exception as e:
    print(f"请求失败: {e}")
    return []
  1. 邮件发送模块
    以QQ邮箱为例,需在设置中生成授权码:

import smtplib
from email.mime.text import MIMEText

def send_email(content):
sender = 'your_qq@qq.com'
receiver = 'recipient@example.com'
password = '你的授权码' # 不是邮箱密码!

msg = MIMEText(f"微博热搜更新:\n{'\n'.join(content)}")
msg['Subject'] = '微博热搜实时推送'
msg['From'] = sender
msg['To'] = receiver

try:
    with smtplib.SMTP_SSL('smtp.qq.com', 465) as server:
        server.login(sender, password)
        server.sendmail(sender, receiver, msg.as_string())
    print("邮件发送成功")
except Exception as e:
    print(f"邮件发送失败: {e}")
  1. 定时任务控制
    使用schedule库实现每30分钟自动执行:

import schedule
import time

def job():
hot_list = get_weibo_hot()
if hot_list:
send_email(hot_list)
else:
print("未获取到热搜数据")

每天9:30执行(示例)

schedule.every().day.at("09:30").do(job)

每30分钟执行一次

schedule.every(30).minutes.do(job)

while True:
schedule.run_pending()
time.sleep(1)

  1. 完整代码整合
    将上述模块组合后,完整脚本约50行:

import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
import schedule
import time

def get_weibo_hot():
headers = {'User-Agent': '你的浏览器标识'}
url = 'https://s.weibo.com/top/summary'
try:
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
hot_list = [item.text for item in soup.select('table.td-02 a')[:10]]
return hot_list
except Exception as e:
print(f"Error: {e}")
return []

def send_email(content):
sender = 'your@qq.com'
receiver = 'target@example.com'
password = '你的授权码'

msg = MIMEText(f"最新热搜:\n{'\n'.join(content)}")
msg['Subject'] = '微博热搜更新'
msg['From'] = sender
msg['To'] = receiver

try:
    with smtplib.SMTP_SSL('smtp.qq.com', 465) as server:
        server.login(sender, password)
        server.sendmail(sender, receiver, msg.as_string())
except Exception as e:
    print(f"Mail Error: {e}")

def job():
hot_data = get_weibo_hot()
if hot_data:
send_email(hot_data)

schedule.every(30).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)

四、运行与调试技巧
首次运行:
安装依赖:pip install requests beautifulsoup4 schedule
手动执行job()函数测试完整流程
常见问题排查:
403错误:检查User-Agent是否模拟浏览器
空数据:确认CSS选择器是否匹配最新页面结构
邮件失败:检查SMTP服务器地址和端口(QQ邮箱为465)
进阶优化:
添加日志记录功能
实现异常自动重试机制
对比历史数据只发送变化内容
五、常见问题Q&A
Q1:被网站封IP怎么办?
A:立即启用备用代理池,建议使用住宅代理(如站大爷IP代理),配合每请求更换IP策略。具体实现可在requests.get()中添加proxies参数:

proxies = {
'http': 'http://123.123.123.123:8080',
'https': 'https://123.123.123.123:8080'
}
response = requests.get(url, headers=headers, proxies=proxies)

Q2:如何获取微博热搜的完整数据?

A:微博部分数据通过AJAX加载,可通过分析网络请求找到数据接口(如https://weibo.com/ajax/side/hotSearch),直接请求JSON数据更稳定:

def get_weibo_json():
url = 'https://weibo.com/ajax/side/hotSearch'
params = {'cv': '1'}
try:
response = requests.get(url, headers=headers, params=params)
data = response.json()['data']['realtime']
return [item['word'] for item in data[:10]]
except Exception as e:
print(f"JSON请求失败: {e}")
return []

Q3:邮件发送失败的可能原因?
A:常见原因包括:

邮箱未开启SMTP服务(需在邮箱设置中手动开启)
使用了错误的授权码(非邮箱登录密码)
发送频率过高被限制(建议间隔≥5分钟)
接收方邮箱将发件人加入黑名单
Q4:如何修改定时任务频率?
A:调整schedule配置即可:

每小时执行一次

schedule.every().hour.do(job)

每天10:30和18:30执行

schedule.every().day.at("10:30").do(job)
schedule.every().day.at("18:30").do(job)

每周一9:00执行

schedule.every().monday.at("09:00").do(job)

Q5:程序运行后自动停止怎么办?
A:可能是未正确处理异常导致循环中断。改进方案:

def job():
try:
hot_data = get_weibo_hot()
if hot_data:
send_email(hot_data)
except Exception as e:
print(f"Job执行出错: {e}")

while True:
try:
schedule.run_pending()
except KeyboardInterrupt:
print("手动停止程序")
break
except Exception as e:
print(f"调度错误: {e}")
time.sleep(1)

六、总结与扩展建议
本方案通过组合基础网络请求和邮件功能,实现了轻量级的热搜监控系统。实际应用中可进一步扩展:

添加数据库存储历史数据
实现多平台通知(微信/钉钉)
开发可视化界面展示热搜趋势
增加关键词过滤功能
技术实现的关键在于平衡效率与稳定性,建议新手先确保基础功能运行正常,再逐步添加复杂特性。遇到问题时,优先检查网络请求状态码和异常日志,大部分错误可通过调整请求参数解决。

目录
相关文章
|
13天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1278 5
|
2天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
12天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1302 87
|
12天前
|
云栖大会
阿里云云栖大会2025年9月24日开启,免费申请大会门票,速度领取~
2025云栖大会将于9月24-26日举行,官网免费预约畅享票,审核后短信通知,持证件入场
1833 13