首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Python爬取公众号文章并实现关键词分析

Python爬取公众号文章并实现关键词分析

作者头像
小白学大数据
发布2025-07-15 14:17:24
发布2025-07-15 14:17:24
24000
代码可运行
举报
文章被收录于专栏:python进阶学习python进阶学习
运行总次数:0
代码可运行

1. 引言

微信公众号是一个重要的内容分发平台,许多优质文章仅在该平台发布。然而,公众号的封闭性使得数据采集和分析变得困难。本文将介绍如何使用Python爬取微信公众号文章,并结合自然语言处理(NLP)技术进行关键词分析,帮助用户快速提取核心信息。

1.1 技术栈
  • 爬虫框架**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">requests</font>** + **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">BeautifulSoup</font>** / **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">mitmproxy</font>**(抓包)
  • 数据处理**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">pandas</font>**
  • 自然语言处理**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">jieba</font>**(中文分词) + **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">wordcloud</font>**(词云生成)
  • 存储**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">sqlite3</font>**(轻量级数据库)
1.2 目标
  1. 爬取指定公众号的历史文章(标题、发布时间、阅读量、正文)。
  2. 对文章内容进行分词和关键词提取。
  3. 生成词云,直观展示高频关键词。

2. 公众号爬取实现

由于微信公众号的反爬机制较强,直接请求网页版可能无法获取数据。我们采用 Fiddler/mitmproxy 抓包 的方式获取真实接口数据。

2.1 抓取公众号文章列表
(1)使用 mitmproxy 获取接口数据

微信公众号的“历史消息”页面(**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">mp.weixin.qq.com</font>**)采用动态加载,可通过抓包工具(如 Fiddler、Charles、mitmproxy)获取真实 API。

步骤:

  1. 在 PC 端微信打开目标公众号的历史文章页面。
  2. 使用 mitmproxy 监听请求,找到类似 **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">https://mp.weixin.qq.com/mp/profile_ext</font>** 的接口。
  3. 分析返回的 JSON 数据,提取文章列表。
(2)Python 代码实现

假设我们已经获取到公众号文章的 API 接口,可以模拟请求获取数据:

代码语言:javascript
代码运行次数:0
运行
复制
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 []

# 测试爬取
articles = get_article_list()
print(json.dumps(articles, indent=2, ensure_ascii=False))

关键点:

  • **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">__biz</font>**:公众号的唯一标识,可在公众号主页 URL 中找到。
  • **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">Cookie</font>**:登录微信 PC 端后,从浏览器开发者工具复制。
2.2 解析文章详情

获取文章列表后,需要进一步爬取每篇文章的正文内容。

代码语言:javascript
代码运行次数:0
运行
复制
from bs4 import BeautifulSoup

def parse_article_detail(article_url):
    resp = requests.get(article_url, 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. 关键词分析

3.1 使用 jieba 进行分词

**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">jieba</font>** 是 Python 中最常用的中文分词工具,支持自定义词典和停用词过滤。

代码语言:javascript
代码运行次数:0
运行
复制
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 生成词云

使用 **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">wordcloud</font>** 库可视化高频关键词:

代码语言:javascript
代码运行次数:0
运行
复制
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))

4. 数据存储(SQLite)

将爬取的文章存储到数据库,方便后续分析:

代码语言:javascript
代码运行次数:0
运行
复制
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()

5. 总结

本文介绍了如何:

  1. 使用 **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">mitmproxy</font>** 抓包获取公众号文章 API。
  2. **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">requests</font>** + **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">BeautifulSoup</font>** 解析文章内容。
  3. 结合 **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">jieba</font>****<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">wordcloud</font>** 进行关键词分析和可视化。
  4. 存储数据至 **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">SQLite</font>** 数据库。
扩展方向
  • 反反爬优化:使用代理 IP、随机 User-Agent 提高稳定性。
  • 自动化监控:定时爬取新文章并发送邮件/Telegram 通知。
  • 情感分析:结合 NLP 模型(如 SnowNLP)分析文章情感倾向。
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-07-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 引言
    • 1.1 技术栈
    • 1.2 目标
  • 2. 公众号爬取实现
    • 2.1 抓取公众号文章列表
      • (1)使用 mitmproxy 获取接口数据
      • (2)Python 代码实现
    • 2.2 解析文章详情
  • 3. 关键词分析
    • 3.1 使用 jieba 进行分词
    • 3.2 生成词云
  • 4. 数据存储(SQLite)
  • 5. 总结
    • 扩展方向
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档