免费编程软件「python+pycharm」
链接:https://pan.quark.cn/s/48a86be2fdc0
一、项目背景与核心目标
微博热搜是大众关注的实时信息窗口,但手动刷新查看效率低下。通过Python自动化技术,我们可以实现热搜数据的定时抓取,并通过邮件实时推送最新内容。本文将分步骤讲解如何用50行代码完成这一功能,重点解决网络请求、数据解析和邮件发送三大核心问题。
二、技术准备清单
Python环境:建议3.8+版本
核心库:
requests:处理HTTP请求
BeautifulSoup:解析HTML内容
smtplib:发送邮件
schedule:定时任务管理
邮箱配置:需开通SMTP服务(以QQ邮箱为例)
三、代码实现四步走
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 []
- 邮件发送模块
以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}")
- 定时任务控制
使用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)
- 完整代码整合
将上述模块组合后,完整脚本约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)
六、总结与扩展建议
本方案通过组合基础网络请求和邮件功能,实现了轻量级的热搜监控系统。实际应用中可进一步扩展:
添加数据库存储历史数据
实现多平台通知(微信/钉钉)
开发可视化界面展示热搜趋势
增加关键词过滤功能
技术实现的关键在于平衡效率与稳定性,建议新手先确保基础功能运行正常,再逐步添加复杂特性。遇到问题时,优先检查网络请求状态码和异常日志,大部分错误可通过调整请求参数解决。