公众号历史文章采集

公众号历史文章采集

前言:采集公众号历史文章,且链接永久有效,亲测2年多无压力。

1.先在 https://mp.weixin.qq.com/ 注册一个个人版使用公众号,供后续使用。
2.点击左侧图文素材,新的创作,写新图文。

请添加图片描述

3.点击超链接后,填入要查询的公众号。

请添加图片描述请添加图片描述

请添加图片描述

4.一个小知识点,通过xpath拿到html源码,并提取正文。
def get_html_code(parseHtml, url, codeXpath):
    code_html = parseHtml.xpath(codeXpath)
    html = ''
    for i in code_html:
        # etree.tostring() #输出修正后的html代码,byte格式
        # 转成utf-8格式,然后decode进行encoding 指定的编码格式解码字符串
        html += etree.tostring(i, encoding='utf-8').decode()
    return html
5.F12抓包分析,发现token和cookie是绑定用户的,生成代码。

搜索公众号接口:query= xxxx
请添加图片描述
请添加图片描述文章链接及翻页接口: fakeid= 搜索公众号对应的id base64编码
若未固定公众号,可将该公众号id做映射表存放,减少请求
请添加图片描述
请添加图片描述

# encoding:utf-8
import json
import math
import time

from spiders.BaseSpider import BaseSpider
from mysqldb.mysql_util import select_link
from parse.requests_parse import requestsParse
from WX.WeChat_util import  parse_bjnews, parseWechat


class WeChatSpider(BaseSpider):
    """
        定义url和请求头
    """
    token = "你的token"

    def __init__(self):
        super().__init__()
        self.cookies = "你的cookie"

        self.params = {
            'action': 'search_biz',
            'begin': '0',
            'count': '50',
            'query': '',
            'fakeid': None,
            'type': 9,
            'token': self.token,
            'lang': 'zh_CN',
            'f': 'json',
            'ajax': '1'
        }

    def next_type(self, token, source, apartment, province, city, district, label):
        begin, count = 0, 1
        self.params["action"] = 'list_ex'
        self.params["query"] = ''
        content = self.get_information('https://mp.weixin.qq.com/cgi-bin/appmsg')
        page = int(math.ceil(json.loads(content).get("app_msg_cnt") / 5))
        #print(page)
        for index in range(page):
            if index % 3 == 0:
                time.sleep(60)
            try:
                if index:
                    begin += 5
                    self.params["begin"] = begin
                    print(f"正在获取第{begin}页数")
                    content = self.get_information('https://mp.weixin.qq.com/cgi-bin/appmsg')
                nextLink = parse_bjnews(content)
                for nextUrl in nextLink:
                    if not token:
                        # select_link 为查询数据库是否存在 增量采集
                        if not select_link(link=nextUrl):
                            break
                    self.nextUrl_q.put(nextUrl)

                if self.nextUrl_q.empty():
                    return

                #日常采集 requestsParse()为解析方法
                t = requestsParse(self.nextUrl_q, source, apartment, province, city, district,
                              titleXpath='//h2[@id="activity-name"]/text()',
                              codeXpath='//*[@id="js_content"]', labeel=label)
                
                if t :
                    return
            except Exception as e:
                print("Spider WeChat Main Error= " + str(e) + " Spider WeChat success page= " + str(
                    count) + ' ' + source)
        return


    def main(self, source, apartment, province, city, district, label):
        
        token = 0   #token为0为增量  1为全量  与select_link()做关联
        self.params["query"] = source
        html = self.get_information('https://mp.weixin.qq.com/cgi-bin/searchbiz')
        print(html)
        self.params["fakeid"] = parseWechat(html)
        self.next_type(token, source, apartment, province, city, district, label)


if __name__ == '__main__':
    WeChatSpider().main("公众号名称", "wechat", "省份", "市", "区",label="industrial_economy_policy")
6.贴出工具类中两个方法.
def parse_bjnews(content):
    content = json.loads(content)
    nextLink = []
    for link in content.get("app_msg_list"):
        # if titleParse(link.get("title")) and title_Wechat(link.get("title")):
        nextLink.append(link.get("link"))
    return nextLink


def parseWechat(html):
    try:
        html = json.loads(html)
        fakeid = html.get("list")[0].get("fakeid")
        return fakeid
    except:
        return
  • 47
    点赞
  • 92
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提取数据并存储,以便后续分析或展示。爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获取。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获取网页的HTML内容。这通常通过HTTP请求库实现,如Python中的Requests库。 解析内容: 爬虫对获取的HTML进行解析,提取有用的信息。常用的解析工具有正则表达式、XPath、Beautiful Soup等。这些工具帮助爬虫定位和提取目标数据,如文本、图片、链接等。 数据存储: 爬虫将提取的数据存储到数据库、文件或其他存储介质中,以备后续分析或展示。常用的存储形式包括关系型数据库、NoSQL数据库、JSON文件等。 遵守规则: 为避免对网站造成过大负担或触发反爬虫机制,爬虫需要遵守网站的robots.txt协议,限制访问频率和深度,并模拟人类访问行为,如设置User-Agent。 反爬虫应对: 由于爬虫的存在,一些网站采取了反爬虫措施,如验证码、IP封锁等。爬虫工程师需要设计相应的策略来应对这些挑战。 爬虫在各个领域都有广泛的应用,包括搜索引擎索引、数据挖掘、价格监测、新闻聚合等。然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,并确保对被访问网站的服务器负责。
根据提供的引用内容,我们可以得知微信公众号的阅读数是通过抓取文章的url链接来获取的。因此,我们可以使用Python爬虫来实现这个功能。具体步骤如下: 1. 首先需要安装requests和BeautifulSoup库,可以使用以下命令进行安装: ```shell pip install requests pip install beautifulsoup4 ``` 2. 接着,我们需要获取微信公众号文章的url链接。可以通过在微信公众号平台上手动获取,或者使用Python爬虫自动获取。 3. 获取到文章的url链接后,我们可以使用requests库发送GET请求获取文章的HTML源代码。 4. 使用BeautifulSoup库解析HTML源代码,找到包含阅读数的标签,并提取出阅读数。 5. 最后,将提取出的阅读数进行输出即可。 下面是一个示例代码,可以获取指定微信公众号最新一篇文章的阅读数: ```python import requests from bs4 import BeautifulSoup # 公众号名称 name = '公众号名称' # 公众号文章页数 page = 1 # 构造请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # 获取指定公众号最新一篇文章的url链接 url = 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=' + biz + '&scene=124&uin=&key=&devicetype=Windows+10&version=62080079&lang=zh_CN&a8scene=0&fontgear=2' # 发送GET请求获取HTML源代码 response = requests.get(url, headers=headers) html = response.text # 使用BeautifulSoup解析HTML源代码 soup = BeautifulSoup(html, 'html.parser') read_num = soup.find('span', {'class': 'read_num'}).get_text() # 输出阅读数 print('最新一篇文章的阅读数为:' + read_num) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Codeooo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值