python 爬取微信文章

yizhihongxing

下面我来为你详细讲解“Python爬取微信文章”的攻略。

本文主要借助Python第三方库beautifulsoup4和requests实现微信公众号文章的爬取。

步骤一:获取微信公众号的历史消息链接

要想爬取微信公众号的文章,首先需要获取该公众号最新或历史消息链接,可以在微信公众平台上手动获取,或者使用第三方API获取。

步骤二:获取每篇文章的链接

通过历史消息链接可以获取公众号中已经发布的所有文章,具体可以使用beautifulsoup4解析历史消息页面,获取所有的文章链接。

import requests
from bs4 import BeautifulSoup

url = "历史消息链接"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
items = soup.find_all(class_="news-list-item")

urls = []
for item in items:
    urls.append(item.find("a")["href"])

步骤三:爬取每篇文章的内容

获取每篇文章链接后,就可以通过requests获取文章的html源代码,然后使用beautifulsoup4解析文章页面,获取文章标题、作者、发布时间、阅读量、点赞量、评论数等信息。另外,由于微信公众号的文章内容大多经过了加密处理,可以通过正则表达式匹配方式解密文章内容。

import re

url = "文章链接"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

# 获取文章标题
title = soup.find("h2", class_="rich_media_title").get_text().strip()

# 获取文章作者和发布时间
meta_content = soup.find("div", class_="rich_media_meta_list").get_text().strip()
pattern = re.compile(r"(.*)\s+(.*)")
result = re.match(pattern, meta_content)
author = result.group(1)
publish_time = result.group(2)

# 获取文章阅读量、点赞量、评论数等信息
read_num = soup.find("span", class_="read_num").get_text().strip()
like_num = soup.find("span", class_="like_num").get_text().strip()
comment_num = soup.find("span", class_="comment_num").get_text().strip()

# 获取文章内容(解密)
content = soup.find("div", class_="rich_media_content").get_text()
pattern = re.compile(r"var\s*sg\:\s*\'(.*?)\';")
result = re.search(pattern, response.text)
if result:
    sg_data = result.group(1)
    content = decode_article(sg_data, content)

print(title, author, publish_time, read_num, like_num, comment_num, content)

其中,decode_article函数可以使用如下代码实现:

def decode_article(sg_data, encrypted_data):
    """
    解密文章内容
    :param sg_data: sg参数
    :param encrypted_data: 加密的文章内容
    :return: 解密后的文章内容
    """
    key = hashlib.md5(sg_data.encode("utf-8")).hexdigest()
    length = len(encrypted_data)
    dec = ''
    for i in range(length):
        key_c = key[i % 32]
        dec_c = chr(ord(key_c) ^ ord(encrypted_data[i]))
        dec += dec_c
    return dec

示例1:爬取“Python之禅”公众号的最新10篇文章

代码如下:

import requests
from bs4 import BeautifulSoup
import re
import hashlib

def decode_article(sg_data, encrypted_data):
    """
    解密文章内容
    :param sg_data: sg参数
    :param encrypted_data: 加密的文章内容
    :return: 解密后的文章内容
    """
    key = hashlib.md5(sg_data.encode("utf-8")).hexdigest()
    length = len(encrypted_data)
    dec = ''
    for i in range(length):
        key_c = key[i % 32]
        dec_c = chr(ord(key_c) ^ ord(encrypted_data[i]))
        dec += dec_c
    return dec

url = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzUxNjQzMTEzMg==&scene=124&#wechat_redirect"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
items = soup.find_all(class_="weui-msg")

urls = []
for item in items:
    urls.append(item.find("a")["href"])

url_prefix = "https://mp.weixin.qq.com"
articles = []
for i in range(10):
    article = {}
    url = url_prefix + urls[i]
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")

    article["title"] = soup.find("h2", class_="rich_media_title").get_text().strip()

    meta_content = soup.find("div", class_="rich_media_meta_list").get_text().strip()
    pattern = re.compile(r"(.*)\s+(.*)")
    result = re.match(pattern, meta_content)
    article["author"] = result.group(1)
    article["pub_time"] = result.group(2)

    article["read_num"] = soup.find("span", class_="read_num").get_text().strip()
    article["like_num"] = soup.find("span", class_="like_num").get_text().strip()
    article["comment_num"] = soup.find("span", class_="comment_num").get_text().strip()

    content = soup.find("div", class_="rich_media_content").get_text()
    pattern = re.compile(r"var\s*sg\:\s*\'(.*?)\';")
    result = re.search(pattern, response.text)
    if result:
        sg_data = result.group(1)
        content = decode_article(sg_data, content)

    article["content"] = content.strip()

    articles.append(article)

for article in articles:
    print(article)

示例2:爬取“骚操作 Python 课”的所有文章

代码如下:

import requests
from bs4 import BeautifulSoup
import re
import hashlib

def decode_article(sg_data, encrypted_data):
    """
    解密文章内容
    :param sg_data: sg参数
    :param encrypted_data: 加密的文章内容
    :return: 解密后的文章内容
    """
    key = hashlib.md5(sg_data.encode("utf-8")).hexdigest()
    length = len(encrypted_data)
    dec = ''
    for i in range(length):
        key_c = key[i % 32]
        dec_c = chr(ord(key_c) ^ ord(encrypted_data[i]))
        dec += dec_c
    return dec

url = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzA3OTk1MjU0Mw==&scene=124&#wechat_redirect"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
items = soup.find_all(class_="weui-msg")

urls = []
for item in items:
    urls.append(item.find("a")["href"])

url_prefix = "https://mp.weixin.qq.com"
articles = []
for i in range(len(urls)):
    article = {}
    url = url_prefix + urls[i]
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")

    article["title"] = soup.find("h2", class_="rich_media_title").get_text().strip()

    meta_content = soup.find("div", class_="rich_media_meta_list").get_text().strip()
    pattern = re.compile(r"(.*)\s+(.*)")
    result = re.match(pattern, meta_content)
    article["author"] = result.group(1)
    article["pub_time"] = result.group(2)

    article["read_num"] = soup.find("span", class_="read_num").get_text().strip()
    article["like_num"] = soup.find("span", class_="like_num").get_text().strip()
    article["comment_num"] = soup.find("span", class_="comment_num").get_text().strip()

    content = soup.find("div", class_="rich_media_content").get_text()
    pattern = re.compile(r"var\s*sg\:\s*\'(.*?)\';")
    result = re.search(pattern, response.text)
    if result:
        sg_data = result.group(1)
        content = decode_article(sg_data, content)

    article["content"] = content.strip()

    articles.append(article)

for article in articles:
    print(article)

以上就是“Python爬取微信文章”的完整攻略,希望能够对你有所帮助。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python 爬取微信文章 - Python技术站

(0)
上一篇 2023年6月3日
下一篇 2023年6月3日

相关文章

  • python实现超级玛丽游戏

    Python实现超级玛丽游戏完整攻略 简介 超级玛丽游戏是经典的2D横板跳跃游戏,此文将讲解如何用Python实现简单的超级玛丽游戏。 前置技能 Python基础语法 Pygame库 实现步骤 安装Pygame库 可以通过pip install命令进行安装,例如: pip install pygame 准备游戏素材 可在网络上搜索“超级玛丽游戏贴图”、“超级…

    python 2023年5月31日
    00
  • python MultipartEncoder传输zip文件实例

    python MultipartEncoder是一个用于构建multipart/form-data请求的模块,可以方便地处理上传文件的数据格式。在使用python进行文件上传时,常常需要用MultipartEncoder将上传的文件打包,然后通过requests.post等方法发送到服务器端。 以下是使用MultipartEncoder传输zip文件的完整攻…

    python 2023年6月3日
    00
  • 如何使用Python连接和操作PostgreSQL数据库?

    在Python中,可以使用psycopg2模块连接和操作PostgreSQL数据库。以下是Python使用psycopg2模块连接和操作PostgreSQL数据库的完整攻略,包括连接PostgreSQL数据库、插入数据、查询数据、更新数据和删除数据等操作。 连接PostgreSQL数据库 在Python中,可以使用psycopg2模块连接PostgreSQL…

    python 2023年5月12日
    00
  • 详解如何使用Python实现删除重复文件

    如何使用 Python 实现删除重复文件? 1. 查找重复文件 使用Python可以很方便地查找重复文件。其中,可以使用hashlib模块计算文件的哈希值,来判断是否为同一个文件。最简单的实现步骤如下所示。 遍历所需要查找的目录,找出其中所有的文件。 对于每一个文件,计算文件的哈希值。 如果哈希值等于目录中的其他某个文件的哈希值,则这两个文件为重复文件。 将…

    python 2023年6月3日
    00
  • Python正则表达式匹配字符串中的数字

    Python正则表达式匹配字符串中的数字 正则表达式是一种用于匹配字符串的强大工具,可以在Python中用于解析HTML、XML等文本数据。本攻略将详细讲解如何使用正则达式匹配字符串中的数字。 正则表达式基本语法 正则表达式是由普通字符和特殊字符组成的字符串,用于描述一类字符串的模式。下面是一些常用的正则表达式特殊字符: .:匹配任意字符,除换行符。 *:匹…

    python 2023年5月14日
    00
  • 浅析python 通⽤爬⾍和聚焦爬⾍

    浅析python 通用爬虫和聚焦爬虫 什么是爬虫 爬虫(Web Crawler),也叫网络爬虫、网络蜘蛛、网络机器人,是一种自动获取网络信息的程序。它能够自动地抓取网页并提取有用的数据。爬虫技术在数据挖掘、搜索引擎、电子商务、信息处理和云计算等领域得到广泛应用。 爬虫的两种方式 通用爬虫 通用爬虫(General Crawler)是一种广泛应用的抓取方式,它…

    python 2023年5月14日
    00
  • python开发之for循环操作实例详解

    当然,我很乐意为您提供“Python开发之for循环操作实例详解”的完整攻略。以下是详细的步骤和示例: Python开发之for循环操作实例详解 在Python中,for循环是一种常用的循环结构,用于遍历可迭代对象中的元素。for循环的语法格式如下: for 变量 in 可迭代对象: 循环体 其中,变量是用于存储可迭代对象中的元素变量名,可迭代对象是一个包含…

    python 2023年5月13日
    00
  • Python 切片索引越界的问题(数组下标越界)

    下面是关于Python切片索引越界问题的完整攻略。 什么是Python切片索引越界问题? 在Python中,切片是一种非常常见的操作,可以通过“:”运算符来获取一段序列的子序列,但是在进行切片操作时,由于下标越界的问题,可能会出现“IndexError: list index out of range”的错误提示。 这种错误提示通常是由于访问了一个不存在的索…

    python 2023年6月5日
    00
合作推广
合作推广
分享本页
返回顶部