- 引言
微信公众号是一个重要的内容分发平台,许多优质文章仅在该平台发布。然而,公众号的封闭性使得数据采集和分析变得困难。本文将介绍如何使用Python爬取微信公众号文章,并结合自然语言处理(NLP)技术进行关键词分析,帮助用户快速提取核心信息。
1.1 技术栈
● 爬虫框架:requests + BeautifulSoup / mitmproxy(抓包)
● 数据处理:pandas
● 自然语言处理:jieba(中文分词) + wordcloud(词云生成)
● 存储:sqlite3(轻量级数据库)
1.2 目标 - 爬取指定公众号的历史文章(标题、发布时间、阅读量、正文)。
- 对文章内容进行分词和关键词提取。
- 生成词云,直观展示高频关键词。
- 公众号爬取实现
由于微信公众号的反爬机制较强,直接请求网页版可能无法获取数据。我们采用 Fiddler/mitmproxy 抓包 的方式获取真实接口数据。
2.1 抓取公众号文章列表
(1)使用 mitmproxy 获取接口数据
微信公众号的“历史消息”页面(mp.weixin.qq.com)采用动态加载,可通过抓包工具(如 Fiddler、Charles、mitmproxy)获取真实 API。
步骤: - 在 PC 端微信打开目标公众号的历史文章页面。
- 使用 mitmproxy 监听请求,找到类似 https://mp.weixin.qq.com/mp/profile_ext 的接口。
- 分析返回的 JSON 数据,提取文章列表。
(2)Python 代码实现
假设我们已经获取到公众号文章的 API 接口,可以模拟请求获取数据:
import requests
import json
from requests.auth import HTTPProxyAuth
代理配置
proxyHost = "www.16yun.cn"
proxyPort = "5445"
proxyUser = "16QMSOML"
proxyPass = "280651"
代理设置(HTTP/HTTPS)
proxies = {
"http": f"http://{proxyUser}:{proxyPass}@{proxyHost}:{proxyPort}",
"https": f"http://{proxyUser}:{proxyPass}@{proxyHost}:{proxyPort}"
}
请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Cookie": "你的Cookie" # 替换为你的微信Cookie
}
def get_article_list(offset=0):
url = "https://mp.weixin.qq.com/mp/profile_ext"
params = {
"action": "getmsg",
"__biz": "公众号的biz参数", # 替换为目标公众号的biz
"offset": offset,
"count": 10, # 每次请求的文章数量
}
try:
# 使用代理发送请求
resp = requests.get(
url,
params=params,
headers=headers,
proxies=proxies,
timeout=10 # 设置超时时间
)
resp.raise_for_status() # 检查请求是否成功
data = resp.json()
return data.get("general_msg_list", [])
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
return []
AI 代码解读
测试爬取
articles = get_article_list()
print(json.dumps(articles, indent=2, ensure_ascii=False))
关键点:
● __biz:公众号的唯一标识,可在公众号主页 URL 中找到。
● Cookie:登录微信 PC 端后,从浏览器开发者工具复制。
2.2 解析文章详情
获取文章列表后,需要进一步爬取每篇文章的正文内容。
from bs4 import BeautifulSoup
def parse_article_detail(article_url):
resp = requests.get(articleurl, headers=headers)
soup = BeautifulSoup(resp.text, 'html.parser')
content = soup.find('div', class='rich_media_content').get_text()
return content.strip()
示例:解析第一篇文章
first_article_url = articles[0]["app_msg_ext_info"]["content_url"]
article_content = parse_article_detail(first_article_url)
print(article_content[:200]) # 输出前200个字符
- 关键词分析
3.1 使用 jieba 进行分词
jieba 是 Python 中最常用的中文分词工具,支持自定义词典和停用词过滤。
import jieba
import jieba.analyse
加载停用词
stopwords = set()
with open("stopwords.txt", "r", encoding="utf-8") as f:
for line in f:
stopwords.add(line.strip())
分词 + 关键词提取
def extract_keywords(text, topK=10):
words = jieba.cut(text)
filtered_words = [word for word in words if word not in stopwords and len(word) > 1]
keywords = jieba.analyse.extract_tags(" ".join(filtered_words), topK=topK)
return keywords
keywords = extract_keywords(article_content)
print("Top 10 关键词:", keywords)
3.2 生成词云
使用 wordcloud 库可视化高频关键词:
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def generate_wordcloud(text):
wc = WordCloud(
font_path="SimHei.ttf", # 中文字体
background_color="white",
max_words=50,
width=800,
height=600
)
wc.generate(text)
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
generate_wordcloud(" ".join(keywords))
- 数据存储(SQLite)
将爬取的文章存储到数据库,方便后续分析:
import sqlite3
conn = sqlite3.connect("wechat_articles.db")
cursor = conn.cursor()
创建表
cursor.execute("""
CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
publish_time TEXT,
read_count INTEGER,
content TEXT,
keywords TEXT
)
""")
插入数据
def save_article(title, publish_time, read_count, content, keywords):
cursor.execute("""
INSERT INTO articles (title, publish_time, read_count, content, keywords)
VALUES (?, ?, ?, ?, ?)
""", (title, publish_time, read_count, content, ",".join(keywords)))
conn.commit()
示例存储
save_article(
title="Python爬虫实战",
publish_time="2023-10-01",
read_count=5000,
content=article_content,
keywords=keywords
)
conn.close()
- 总结
本文介绍了如何: - 使用 mitmproxy 抓包获取公众号文章 API。
- 用 requests + BeautifulSoup 解析文章内容。
- 结合 jieba 和 wordcloud 进行关键词分析和可视化。
- 存储数据至 SQLite 数据库。
扩展方向
● 反反爬优化:使用代理 IP、随机 User-Agent 提高稳定性。
● 自动化监控:定时爬取新文章并发送邮件/Telegram 通知。
● 情感分析:结合 NLP 模型(如 SnowNLP)分析文章情感倾向。