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

一、项目背景与核心目标

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

二、技术准备清单

  1. Python环境:建议3.8+版本

  2. 核心库

    • requests:处理HTTP请求
    • BeautifulSoup:解析HTML内容
    • smtplib:发送邮件
    • schedule:定时任务管理
  3. 邮箱配置:需开通SMTP服务(以QQ邮箱为例)

三、代码实现四步走

1. 破解网页请求

微博热搜页面(s.weibo.com/top/summary...

python 复制代码
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 []
markdown 复制代码
2. 邮件发送模块

以QQ邮箱为例,需在设置中生成授权码:

python 复制代码
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}")
markdown 复制代码
3. 定时任务控制

使用schedule库实现每30分钟自动执行:

scss 复制代码
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)
markdown 复制代码
4. 完整代码整合

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

python 复制代码
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)

四、运行与调试技巧

  1. 首次运行

    • 安装依赖:pip install requests beautifulsoup4 schedule
    • 手动执行job()函数测试完整流程
  2. 常见问题排查

    • 403错误:检查User-Agent是否模拟浏览器
    • 空数据:确认CSS选择器是否匹配最新页面结构
    • 邮件失败:检查SMTP服务器地址和端口(QQ邮箱为465)
  3. 进阶优化

    • 添加日志记录功能
    • 实现异常自动重试机制
    • 对比历史数据只发送变化内容

五、常见问题Q&A

Q1:被网站封IP怎么办?

A:立即启用备用代理池,建议使用住宅代理(如站大爷IP代理),配合每请求更换IP策略。具体实现可在requests.get()中添加proxies参数:

rust 复制代码
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数据更稳定:

csharp 复制代码
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配置即可:

scss 复制代码
# 每小时执行一次
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:可能是未正确处理异常导致循环中断。改进方案:

python 复制代码
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)

六、总结与扩展建议

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

  • 添加数据库存储历史数据
  • 实现多平台通知(微信/钉钉)
  • 开发可视化界面展示热搜趋势
  • 增加关键词过滤功能

技术实现的关键在于平衡效率与稳定性,建议新手先确保基础功能运行正常,再逐步添加复杂特性。遇到问题时,优先检查网络请求状态码和异常日志,大部分错误可通过调整请求参数解决。

相关推荐
liliangcsdn1 小时前
python如何写数据到excel示例
开发语言·python·excel
CNRio1 小时前
将word和excel快速转换为markdown格式
python·word·excel
小白银子4 小时前
零基础从头教学Linux(Day 52)
linux·运维·服务器·python·python3.11
AAA小肥杨5 小时前
基于k8s的Python的分布式深度学习训练平台搭建简单实践
人工智能·分布式·python·ai·kubernetes·gpu
lichong9517 小时前
Git 检出到HEAD 再修改提交commit 会消失解决方案
java·前端·git·python·github·大前端·大前端++
Tiny番茄7 小时前
31.下一个排列
数据结构·python·算法·leetcode
小白学大数据8 小时前
实战:Python爬虫如何模拟登录与维持会话状态
开发语言·爬虫·python
FriendshipT8 小时前
目标检测:使用自己的数据集微调DEIMv2进行物体检测
人工智能·pytorch·python·目标检测·计算机视觉
平谷一勺8 小时前
数据清洗-缺失值的处理
python·数据分析
末世灯光9 小时前
时间序列入门第一问:它和普通数据有什么不一样?(附 3 类典型案例)
人工智能·python·机器学习·时序数据