Browse Source

first push

wangkun 2 years ago
parent
commit
bf476c4b69
10 changed files with 1087 additions and 0 deletions
  1. 3 0
      logs/__init__.py
  2. 3 0
      main/__init__.py
  3. 157 0
      main/common.py
  4. 26 0
      main/demo.py
  5. 405 0
      main/feishu_lib.py
  6. 187 0
      main/haokan_hot.py
  7. 15 0
      main/haokan_play.py
  8. 261 0
      main/haokan_publish.py
  9. 27 0
      main/run_haokan_hot.py
  10. 3 0
      videos/__init__.py

+ 3 - 0
logs/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/23

+ 3 - 0
main/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/23

+ 157 - 0
main/common.py

@@ -0,0 +1,157 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/23
+"""
+公共方法,包含:生成log / 删除log / 下载方法 / 读取文件 / 统计下载数
+"""
+from datetime import date, timedelta
+from loguru import logger
+import datetime
+import os
+import time
+import requests
+import urllib3
+proxies = {"http": None, "https": None}
+
+
+class Common:
+    # 统一获取当前时间 <class 'datetime.datetime'>  2022-04-14 20:13:51.244472
+    now = datetime.datetime.now()
+    # 昨天 <class 'str'>  2022-04-13
+    yesterday = (date.today() + timedelta(days=-1)).strftime("%Y/%m/%d")
+    # 今天 <class 'datetime.date'>  2022-04-14
+    today = date.today()
+    # 明天 <class 'str'>  2022-04-15
+    tomorrow = (date.today() + timedelta(days=1)).strftime("%Y/%m/%d")
+
+    # 使用 logger 模块生成日志
+    @staticmethod
+    def logger(log_type):
+        """
+        使用 logger 模块生成日志
+        """
+        # 日志路径
+        log_dir = r"./logs/"
+        log_path = os.getcwd() + os.sep + log_dir
+        if not os.path.isdir(log_path):
+            os.makedirs(log_path)
+
+        # 日志文件名
+        log_name = time.strftime("%Y-%m-%d", time.localtime(time.time())) + '-haokan-'+str(log_type)+'.log'
+
+        # 日志不打印到控制台
+        logger.remove(handler_id=None)
+
+        # rotation="500 MB",实现每 500MB 存储一个文件
+        # rotation="12:00",实现每天 12:00 创建一个文件
+        # rotation="1 week",每周创建一个文件
+        # retention="10 days",每隔10天之后就会清理旧的日志
+        # 初始化日志
+        logger.add(log_dir + log_name, level="INFO", rotation='00:00')
+
+        return logger
+
+    # 清除日志,保留最近 10 个文件
+    @classmethod
+    def del_logs(cls, log_type):
+        """
+        清除冗余日志文件
+        :return: 保留最近 10 个日志
+        """
+        log_dir = "./logs/"
+        all_files = sorted(os.listdir(log_dir))
+        all_logs = []
+        for log in all_files:
+            name = os.path.splitext(log)[-1]
+            if name == ".log":
+                all_logs.append(log)
+
+        if len(all_logs) <= 10:
+            pass
+        else:
+            for file in all_logs[:len(all_logs) - 10]:
+                os.remove(log_dir + file)
+        cls.logger(log_type).info("清除日志成功")
+
+    # 删除 charles 缓存文件,只保留最近的两个文件
+    @classmethod
+    def del_charles_files(cls, log_type):
+        # 目标文件夹下所有文件
+        all_file = sorted(os.listdir("./chlsfiles/"))
+        for file in all_file[0:-3]:
+            os.remove(r"./chlsfiles/" + file)
+        cls.logger(log_type).info("删除 charles 缓存文件成功")
+
+    # 封装下载视频或封面的方法
+    @classmethod
+    def download_method(cls, log_type, text, d_name, d_url):
+        """
+        下载封面:text == "cover" ; 下载视频:text == "video"
+        需要下载的视频标题:d_title
+        视频封面,或视频播放地址:d_url
+        下载保存路径:"./files/{d_title}/"
+        """
+        videos_dir = r"./videos/"
+        if not os.path.exists(videos_dir):
+            os.mkdir(videos_dir)
+        # 首先创建一个保存该视频相关信息的文件夹
+        video_dir = "./videos/" + str(d_name) + "/"
+        if not os.path.exists(video_dir):
+            os.mkdir(video_dir)
+
+        # 下载视频
+        if text == "video":
+            # 需要下载的视频地址
+            video_url = str(d_url).replace('http://', 'https://')
+            # 视频名
+            video_name = "video1.mp4"
+
+            # 下载视频
+            urllib3.disable_warnings()
+            response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
+            try:
+                with open(video_dir + video_name, "wb") as f:
+                    for chunk in response.iter_content(chunk_size=10240):
+                        f.write(chunk)
+                cls.logger(log_type).info("==========视频下载完成==========")
+            except Exception as e:
+                cls.logger(log_type).error(f"视频下载失败:{e}\n")
+
+        # 下载音频
+        elif text == "audio":
+            # 需要下载的视频地址
+            audio_url = str(d_url).replace('http://', 'https://')
+            # 音频名
+            audio_name = "audio1.mp4"
+
+            # 下载视频
+            urllib3.disable_warnings()
+            response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
+            try:
+                with open(video_dir + audio_name, "wb") as f:
+                    for chunk in response.iter_content(chunk_size=10240):
+                        f.write(chunk)
+                cls.logger(log_type).info("==========音频下载完成==========")
+            except Exception as e:
+                cls.logger(log_type).error(f"音频下载失败:{e}\n")
+
+        # 下载封面
+        elif text == "cover":
+            # 需要下载的封面地址
+            cover_url = str(d_url)
+            # 封面名
+            cover_name = "image.jpg"
+
+            # 下载封面
+            urllib3.disable_warnings()
+            response = requests.get(cover_url, proxies=proxies, verify=False)
+            try:
+                with open(video_dir + cover_name, "wb") as f:
+                    f.write(response.content)
+                cls.logger(log_type).info("==========封面下载完成==========")
+            except Exception as e:
+                cls.logger(log_type).error(f"封面下载失败:{e}\n")
+
+
+if __name__ == "__main__":
+    common = Common()

+ 26 - 0
main/demo.py

@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/23
+import time
+
+from main.feishu_lib import Feishu
+
+
+class Demo:
+    @classmethod
+    def get_sheet(cls, log_type, crawler, sheetid):
+        sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
+        print(sheet)
+
+    @classmethod
+    def publish_time(cls):
+        time1 = '发布时间:2022年11月20日'
+        time2 = time1.replace('发布时间:', '').replace('年', '/').replace('月', '/').replace('日', '')
+        print(time2)
+        time3 = int(time.mktime(time.strptime(time2, "%Y/%m/%d")))
+        print(time3)
+
+
+if __name__ == '__main__':
+    # Demo.get_sheet('demo', 'haokan', 'TaQXk3')
+    Demo.publish_time()

+ 405 - 0
main/feishu_lib.py

@@ -0,0 +1,405 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/23
+import json
+import requests
+import urllib3
+from main.common import Common
+proxies = {"http": None, "https": None}
+
+
+class Feishu:
+    """
+    编辑飞书云文档
+    """
+    # 看一看爬虫数据表
+    kanyikan_url = "https://w42nne6hzg.feishu.cn/sheets/shtcngRPoDYAi24x52j2nDuHMih?"
+    # 快手爬虫数据表
+    kuaishou_url = "https://w42nne6hzg.feishu.cn/sheets/shtcnICEfaw9llDNQkKgdymM1xf?"
+    # 微视爬虫数据表
+    weishi_url = "https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?"
+    # 小年糕爬虫数据表
+    xiaoniangao_url = "https://w42nne6hzg.feishu.cn/sheets/shtcnYxiyQ1wLklo1W5Kdqc9cGh?"
+    # 数据监控表
+    crawler_monitor = "https://w42nne6hzg.feishu.cn/sheets/shtcnlZWYazInhf7Z60jkbLRJyd?"
+    # 西瓜视频表
+    crawler_xigua = 'https://w42nne6hzg.feishu.cn/sheets/shtcnvOpx2P8vBXiV91Ot1MKIw8?'
+    # 好看视频表
+    crawler_haokan = 'https://w42nne6hzg.feishu.cn/sheets/shtcnaYz8Nhv8q6DbWtlL6rMEBd?'
+
+    # 手机号
+    wangkun = "13426262515"
+    gaonannan = "18501180073"
+    xinxin = "15546206651"
+    huxinxue = "18832292015"
+
+    # 飞书路径token
+    @classmethod
+    def spreadsheettoken(cls, crawler):
+        """
+        :param crawler: 哪个爬虫
+        """
+        if crawler == "kanyikan":
+            return "shtcngRPoDYAi24x52j2nDuHMih"
+        elif crawler == "kuaishou":
+            return "shtcnICEfaw9llDNQkKgdymM1xf"
+        elif crawler == "weishi":
+            return "shtcn5YSWg91JfVGzj0SFZIRRPh"
+        elif crawler == "xiaoniangao":
+            return "shtcnYxiyQ1wLklo1W5Kdqc9cGh"
+        elif crawler == "monitor":
+            return "shtcnlZWYazInhf7Z60jkbLRJyd"
+        elif crawler == "xigua":
+            return "shtcnvOpx2P8vBXiV91Ot1MKIw8"
+        elif crawler == 'haokan':
+            return 'shtcnaYz8Nhv8q6DbWtlL6rMEBd'
+
+    # 获取飞书api token
+    @classmethod
+    def get_token(cls, log_type):
+        """
+        获取飞书api token
+        :return:
+        """
+        url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
+        post_data = {"app_id": "cli_a13ad2afa438d00b",  # 这里账号密码是发布应用的后台账号及密码
+                     "app_secret": "4tK9LY9VbiQlY5umhE42dclBFo6t4p5O"}
+
+        try:
+            urllib3.disable_warnings()
+            response = requests.post(url=url, data=post_data, proxies=proxies, verify=False)
+            tenant_access_token = response.json()["tenant_access_token"]
+            return tenant_access_token
+        except Exception as e:
+            Common.logger(log_type).error("获取飞书 api token 异常:{}", e)
+
+    # 获取表格元数据
+    @classmethod
+    def get_metainfo(cls, log_type, crawler):
+        """
+        获取表格元数据
+        :return:
+        """
+        get_metainfo_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                           + cls.spreadsheettoken(crawler) + "/metainfo"
+
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        params = {
+            "extFields": "protectedRange",  # 额外返回的字段,extFields=protectedRange时返回保护行列信息
+            "user_id_type": "open_id"  # 返回的用户id类型,可选open_id,union_id
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.get(url=get_metainfo_url, headers=headers, params=params, proxies=proxies, verify=False)
+            response = json.loads(r.content.decode("utf8"))
+            return response
+        except Exception as e:
+            Common.logger(log_type).error("获取表格元数据异常:{}", e)
+
+    # 读取工作表中所有数据
+    @classmethod
+    def get_values_batch(cls, log_type, crawler, sheetid):
+        """
+        读取工作表中所有数据
+        :param log_type: 启用哪个 log
+        :param crawler: 哪个爬虫
+        :param sheetid: 哪张表
+        :return: 所有数据
+        """
+        get_values_batch_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                               + cls.spreadsheettoken(crawler) + "/values_batch_get"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        params = {
+            # 多个查询范围 如 url?ranges=range1,range2 ,其中 range 包含 sheetId 与单元格范围两部分
+            "ranges": sheetid,
+
+            # valueRenderOption=ToString 可返回纯文本的值(数值类型除外);
+            # valueRenderOption=FormattedValue 计算并格式化单元格;
+            # valueRenderOption=Formula单元格中含有公式时返回公式本身;
+            # valueRenderOption=UnformattedValue计算但不对单元格进行格式化
+            "valueRenderOption": "ToString",
+
+            # dateTimeRenderOption=FormattedString 计算并将时间日期按照其格式进行格式化,但不会对数字进行格式化,返回格式化后的字符串。
+            "dateTimeRenderOption": "",
+
+            # 返回的用户id类型,可选open_id,union_id
+            "user_id_type": "open_id"
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.get(url=get_values_batch_url, headers=headers, params=params, proxies=proxies, verify=False)
+            # print(r.text)
+            response = json.loads(r.content.decode("utf8"))
+            values = response["data"]["valueRanges"][0]["values"]
+            return values
+        except Exception as e:
+            Common.logger(log_type).error("读取工作表所有数据异常:{}", e)
+
+    # 工作表,插入行或列
+    @classmethod
+    def insert_columns(cls, log_type, crawler, sheetid, majordimension, startindex, endindex):
+        """
+        工作表插入行或列
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫的云文档
+        :param sheetid:哪张工作表
+        :param majordimension:行或者列, ROWS、COLUMNS
+        :param startindex:开始位置
+        :param endindex:结束位置
+        """
+        insert_columns_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                             + cls.spreadsheettoken(crawler) + "/insert_dimension_range"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        body = {
+            "dimension": {
+                "sheetId": sheetid,
+                "majorDimension": majordimension,  # 默认 ROWS ,可选 ROWS、COLUMNS
+                "startIndex": startindex,  # 开始的位置
+                "endIndex": endindex  # 结束的位置
+            },
+            "inheritStyle": "AFTER"  # BEFORE 或 AFTER,不填为不继承 style
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.post(url=insert_columns_url, headers=headers, json=body, proxies=proxies, verify=False)
+            Common.logger(log_type).info("插入行或列:{}", r.json()["msg"])
+        except Exception as e:
+            Common.logger(log_type).error("插入行或列异常:{}", e)
+
+    # 写入数据
+    @classmethod
+    def update_values(cls, log_type, crawler, sheetid, ranges, values):
+        """
+        写入数据
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫的云文档
+        :param sheetid:哪张工作表
+        :param ranges:单元格范围
+        :param values:写入的具体数据,list
+        """
+        update_values_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                            + cls.spreadsheettoken(crawler) + "/values_batch_update"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        body = {
+            "valueRanges": [
+                {
+                    "range": sheetid + "!" + ranges,
+                    "values": values
+                },
+            ],
+        }
+
+        try:
+            urllib3.disable_warnings()
+            r = requests.post(url=update_values_url, headers=headers, json=body, proxies=proxies, verify=False)
+            Common.logger(log_type).info("写入数据:{}", r.json()["msg"])
+        except Exception as e:
+            Common.logger(log_type).error("写入数据异常:{}", e)
+
+    # 合并单元格
+    @classmethod
+    def merge_cells(cls, log_type, crawler, sheetid, ranges):
+        """
+        合并单元格
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫
+        :param sheetid:哪张工作表
+        :param ranges:需要合并的单元格范围
+        """
+        merge_cells_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                          + cls.spreadsheettoken(crawler) + "/merge_cells"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+
+        body = {
+            "range": sheetid + "!" + ranges,
+            "mergeType": "MERGE_ROWS"
+        }
+
+        try:
+            urllib3.disable_warnings()
+            r = requests.post(url=merge_cells_url, headers=headers, json=body, proxies=proxies, verify=False)
+            Common.logger(log_type).info("合并单元格:{}", r.json()["msg"])
+        except Exception as e:
+            Common.logger(log_type).error("合并单元格异常:{}", e)
+
+    # 读取单元格数据
+    @classmethod
+    def get_range_value(cls, log_type, crawler, sheetid, cell):
+        """
+        读取单元格内容
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫
+        :param sheetid: 哪张工作表
+        :param cell: 哪个单元格
+        :return: 单元格内容
+        """
+        get_range_value_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                              + cls.spreadsheettoken(crawler) + "/values/" + sheetid + "!" + cell
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        params = {
+            # valueRenderOption=ToString 可返回纯文本的值(数值类型除外);
+            # valueRenderOption=FormattedValue 计算并格式化单元格;
+            # valueRenderOption=Formula 单元格中含有公式时返回公式本身;
+            # valueRenderOption=UnformattedValue 计算但不对单元格进行格式化。
+            "valueRenderOption": "FormattedValue",
+
+            # dateTimeRenderOption=FormattedString 计算并对时间日期按照其格式进行格式化,但不会对数字进行格式化,返回格式化后的字符串。
+            "dateTimeRenderOption": "",
+
+            # 返回的用户id类型,可选open_id,union_id
+            "user_id_type": "open_id"
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.get(url=get_range_value_url, headers=headers, params=params, proxies=proxies, verify=False)
+            # print(r.text)
+            return r.json()["data"]["valueRange"]["values"][0]
+        except Exception as e:
+            Common.logger(log_type).error("读取单元格数据异常:{}", e)
+
+    # 删除行或列,可选 ROWS、COLUMNS
+    @classmethod
+    def dimension_range(cls, log_type, crawler, sheetid, major_dimension, startindex, endindex):
+        """
+        删除行或列
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫
+        :param sheetid:工作表
+        :param major_dimension:默认 ROWS ,可选 ROWS、COLUMNS
+        :param startindex:开始的位置
+        :param endindex:结束的位置
+        :return:
+        """
+        dimension_range_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                              + cls.spreadsheettoken(crawler) + "/dimension_range"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        body = {
+            "dimension": {
+                "sheetId": sheetid,
+                "majorDimension": major_dimension,
+                "startIndex": startindex,
+                "endIndex": endindex
+            }
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.delete(url=dimension_range_url, headers=headers, json=body, proxies=proxies, verify=False)
+            Common.logger(log_type).info("删除视频数据:{}", r.json()["msg"])
+        except Exception as e:
+            Common.logger(log_type).error("删除视频数据异常:{}", e)
+
+    # 获取用户 ID
+    @classmethod
+    def get_userid(cls, log_type, username):
+        try:
+            url = "https://open.feishu.cn/open-apis/user/v1/batch_get_id?"
+            headers = {
+                "Authorization": "Bearer " + cls.get_token(log_type),
+                "Content-Type": "application/json; charset=utf-8"
+            }
+            if username == "wangkun":
+                username = cls.wangkun
+            elif username == "gaonannan":
+                username = cls.gaonannan
+            elif username == "xinxin":
+                username = cls.xinxin
+            elif username == "huxinxue":
+                username = cls.huxinxue
+            data = {"mobiles": [username]}
+            urllib3.disable_warnings()
+            r = requests.get(url=url, headers=headers, params=data, verify=False, proxies=proxies)
+            open_id = r.json()["data"]["mobile_users"][username][0]["open_id"]
+            Common.logger(log_type).info("{}:{}", username, open_id)
+            # print(f"{username}:{open_id}")
+            return open_id
+        except Exception as e:
+            Common.logger(log_type).error("get_userid异常:{}", e)
+
+    # 飞书机器人
+    @classmethod
+    def bot(cls, log_type, content):
+        try:
+            url = "https://open.feishu.cn/open-apis/bot/v2/hook/96989577-50e7-4653-9ec2-308fe3f2c5fe"
+            headers = {
+                'Content-Type': 'application/json'
+            }
+            data = json.dumps({
+                "msg_type": "interactive",
+                "card": {
+                    "config": {
+                        "wide_screen_mode": True,
+                        "enable_forward": True
+                    },
+                    "elements": [{
+                        "tag": "div",
+                        "text": {
+                            "content": "\n<at id=" + str(cls.get_userid(log_type, "wangkun")) + "></at>\n" + content,
+                            "tag": "lark_md"
+                        }
+                    }, {
+                        "actions": [{
+                            "tag": "button",
+                            "text": {
+                                "content": "快手爬虫表",
+                                "tag": "lark_md"
+                            },
+                            "url": "https://w42nne6hzg.feishu.cn/sheets/shtcnICEfaw9llDNQkKgdymM1xf",
+                            "type": "default",
+                            "value": {}
+                        },
+                            {
+                                "tag": "button",
+                                "text": {
+                                    "content": "快手Jenkins",
+                                    "tag": "lark_md"
+                                },
+                                "url": "https://jenkins-on.yishihui.com/view/%E7%88%AC%E8%99%AB-Spider/job/%E5%BF%"
+                                       "AB%E6%89%8B%E5%B0%8F%E7%A8%8B%E5%BA%8F-%E8%A7%86%E9%A2%91%E7%88%AC%E5%8F%96/",
+                                "type": "default",
+                                "value": {}
+                            }
+
+                        ],
+                        "tag": "action"
+                    }],
+                    "header": {
+                        "title": {
+                            "content": "📣有新的报警,请注意查处",
+                            "tag": "plain_text"
+                        }
+                    }
+                }
+            })
+            urllib3.disable_warnings()
+            r = requests.post(url, headers=headers, data=data, verify=False, proxies=proxies)
+            Common.logger(log_type).info("触发机器人消息:{}, {}", r, r.json()["StatusMessage"])
+        except Exception as e:
+            Common.logger(log_type).error("bot异常:{}", e)
+
+
+if __name__ == "__main__":
+    Feishu.bot("kuaishou", "我是快手测试内容,请忽略")
+    # Feishu.get_userid("kuaishou", "huxinxue")
+    # Feishu.get_department("kuaishou")
+    pass

+ 187 - 0
main/haokan_hot.py

@@ -0,0 +1,187 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/23
+import os
+import sys
+import time
+import requests
+sys.path.append(os.getcwd())
+from main.common import Common
+from main.feishu_lib import Feishu
+from main.haokan_publish import Publish
+
+
+class Hot:
+
+    page = 0
+
+    @classmethod
+    def get_hot_feeds(cls, log_type, our_id, env):
+        while True:
+            cls.page += 1
+            url = 'https://haokan.baidu.com/videoui/page/pc/toplist?'
+            headers = {
+                'Accept-Encoding': 'gzip, deflate, br',
+                'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
+                'Cache-Control': 'no-cache',
+                'Content-Type': 'application/x-www-form-urlencoded',
+                'Cookie': 'BIDUPSID=0C817797C726E2312710D870ECDAE8A2; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; PSTM=1669001132; BAIDUID=AB7069CAF9ECB7AA43E400D164119733:FG=1; BDSFRCVID=H54OJexroG0GmHrjfnewtKf1EeKK0gOTDYLEJs2qYShnrsPVJeC6EG0PtoWQkz--EHtdogKK0mOTHv8F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF=tR333R7oKRu_HRjYbb__-P4DePAttURZ56bHWh0M3b61qRcIh4ob5MPEDto-BMPj52OnKUT13lc5h4jX0P7_KRtr346-35543bRTLn76LRv0Kj6HybOfhP-UyN3LWh37bJblMKoaMp78jR093JO4y4Ldj4oxJpOJ5JbMopCafJOKHICGDTA-jMK; Hm_lvt_4aadd610dfd2f5972f1efee2653a2bc5=1669029805; PC_TAB_LOG=video_details_page; COMMON_LID=88bc9b0fbce964fbb6a76cfd7927d02b; hkpcvideolandquery=%u4E2D%u56FD%u7537%u513F%u5218%u5F3A%u6012%u70E7%u9756%u56FD%u795E%u793E%uFF0C%u518D%u70E7%u65E5%u672C%u9A7B%u97E9%u5927%u4F7F%u9986%uFF0C%u540E%u6765%u600E%u4E48%u6837%u4E86%uFF1F; BDSFRCVID_BFESS=H54OJexroG0GmHrjfnewtKf1EeKK0gOTDYLEJs2qYShnrsPVJeC6EG0PtoWQkz--EHtdogKK0mOTHv8F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF_BFESS=tR333R7oKRu_HRjYbb__-P4DePAttURZ56bHWh0M3b61qRcIh4ob5MPEDto-BMPj52OnKUT13lc5h4jX0P7_KRtr346-35543bRTLn76LRv0Kj6HybOfhP-UyN3LWh37bJblMKoaMp78jR093JO4y4Ldj4oxJpOJ5JbMopCafJOKHICGDTA-jMK; H_PS_PSSID=36557_37769_34813_37778_37728_36806_37719_37743_26350_37787; PSINO=2; delPer=0; BA_HECTOR=8la125a48ka00la4agal0he91hnre381e; BAIDUID_BFESS=AB7069CAF9ECB7AA43E400D164119733:FG=1; ZFY=e8fgayH:A:A8S2QAjzqo6RRIm7t3wLMhAdtluiJeCoSc4:C; Hm_lpvt_4aadd610dfd2f5972f1efee2653a2bc5=1669206505; ariaDefaultTheme=undefined; RT="z=1&dm=baidu.com&si=7jsviskg99&ss=latmgdwn&sl=1&tt=10y&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=1tl"',
+                'Pragma': 'no-cache',
+                'Referer': 'https://haokan.baidu.com/',
+                'Sec-Fetch-Dest': 'empty',
+                'Sec-Fetch-Mode': 'cors',
+                'Sec-Fetch-Site': 'same-origin',
+                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.52',
+                'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
+                'sec-ch-ua-mobile': '?0',
+                'sec-ch-ua-platform': '"macOS"'
+            }
+            params = {
+                'type': 'hotvideo',
+                'sfrom': 'haokan_web_banner',
+                'pageSize': '20',
+                '_format': 'json',
+                'page': str(cls.page)
+            }
+            r = requests.get(url=url, headers=headers, params=params)
+            if r.json()['errno'] != 0 or r.json()['error'] != '成功':
+                Common.logger(log_type).error(f'feeds_response:{r.text}\n')
+            elif len(r.json()['apiData']['response']['video']) == 0:
+                Common.logger(log_type).info(f'没有新数据了\n')
+                return
+            else:
+                feeds = r.json()['apiData']['response']['video']
+                Common.logger(log_type).info(f'正在抓取第{cls.page}页\n')
+                for i in range(len(feeds)):
+                    # video_title
+                    if 'title' not in feeds[i]:
+                        video_title = 0
+                    else:
+                        video_title = feeds[i]['title']
+
+                    # video_id
+                    if 'vid' not in feeds[i]:
+                        video_id = 0
+                    else:
+                        video_id = feeds[i]['vid']
+
+                    # duration
+                    if 'duration' not in feeds[i]:
+                        duration = 0
+                    else:
+                        duration = feeds[i]['duration']
+
+                    # publish_time
+                    if 'publish_time' not in feeds[i]:
+                        publish_time = 0
+                    else:
+                        publish_time = feeds[i]['publish_time']\
+                            .replace('发布时间:', '').replace('年', '/').replace('月', '/').replace('日', '')
+
+                    # user_name
+                    if 'author' not in feeds[i]:
+                        user_name = 0
+                    else:
+                        user_name = feeds[i]['author']
+
+                    # head_url
+                    if 'author_icon' not in feeds[i]:
+                        head_url = 0
+                    else:
+                        head_url = feeds[i]['author_icon']
+
+                    # cover_url
+                    if 'poster' not in feeds[i]:
+                        cover_url = 0
+                    else:
+                        cover_url = feeds[i]['poster']
+
+                    # video_url
+                    if 'videoUrl' not in feeds[i]:
+                        video_url = 0
+                    else:
+                        video_url = feeds[i]['videoUrl']
+
+                    Common.logger(log_type).info(f'video_title:{video_title}')
+                    Common.logger(log_type).info(f'video_id:{video_id}')
+                    Common.logger(log_type).info(f'duration:{duration}')
+                    Common.logger(log_type).info(f'publish_time:{publish_time}')
+                    Common.logger(log_type).info(f'user_name:{user_name}')
+                    Common.logger(log_type).info(f'head_url:{head_url}')
+                    Common.logger(log_type).info(f'cover_url:{cover_url}')
+                    Common.logger(log_type).info(f'video_url:{video_url}\n')
+
+                    video_dict = {'video_title': video_title,
+                                  'video_id': video_id,
+                                  'duration': duration,
+                                  'publish_time': publish_time,
+                                  'user_name': user_name,
+                                  'head_url': head_url,
+                                  'cover_url': cover_url,
+                                  'video_url': video_url}
+                    cls.download_publish(log_type, video_dict, our_id, env)
+
+                time.sleep(5)
+
+    @classmethod
+    def download_publish(cls, log_type, video_dict, our_id, env):
+        if video_dict['video_title'] == 0 or video_dict['video_url'] == 0:
+            Common.logger(log_type).info('无效视频\n')
+        elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(log_type, 'haokan', '5pWipX') for x in y]:
+            Common.logger(log_type).info('视频已下载\n')
+        else:
+            # 下载
+            Common.download_method(log_type, 'cover', video_dict['video_title'], video_dict['cover_url'])
+            Common.download_method(log_type, 'video', video_dict['video_title'], video_dict['video_url'])
+            with open("./videos/" + video_dict['video_title']
+                      + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
+                f_a.write(str(video_dict['video_id']) + "\n" +
+                          str(video_dict['video_title']) + "\n" +
+                          str(video_dict['duration']) + "\n" +
+                          '0' + "\n" +
+                          '0' + "\n" +
+                          '0' + "\n" +
+                          '0' + "\n" +
+                          '1920*1080' + "\n" +
+                          str(int(time.mktime(time.strptime(video_dict['publish_time'], "%Y/%m/%d")))) + "\n" +
+                          str(video_dict['user_name']) + "\n" +
+                          str(video_dict['head_url']) + "\n" +
+                          str(video_dict['video_url']) + "\n" +
+                          str(video_dict['cover_url']) + "\n" +
+                          "HAOKAN" + str(int(time.time())))
+            Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
+
+            # 上传
+            Common.logger(log_type).info(f"开始上传视频:{video_dict['video_title']}")
+            if env == 'dev':
+                our_video_id = Publish.upload_and_publish(log_type, our_id, env)
+                our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
+            else:
+                our_video_id = Publish.upload_and_publish(log_type, env, "width")
+                our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
+            Common.logger(log_type).info(f"视频上传完成:{video_dict['video_title']}\n")
+
+            # 保存视频信息至云文档
+            Common.logger(log_type).info(f"保存视频至已下载表:{video_dict['video_title']}")
+            Feishu.insert_columns(log_type, "haokan", "5pWipX", "ROWS", 1, 2)
+            upload_time = int(time.time())
+            values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
+                       "今日热播榜",
+                       video_dict['video_title'],
+                       video_dict['video_id'],
+                       our_video_link,
+                       video_dict['duration'],
+                       video_dict['publish_time'],
+                       video_dict['user_name'],
+                       video_dict['head_url'],
+                       video_dict['cover_url'],
+                       video_dict['video_url']]]
+            time.sleep(1)
+            Feishu.update_values(log_type, "haokan", "5pWipX", "F2:Z2", values)
+            Common.logger(log_type).info(f"视频:{video_dict['video_title']},下载/上传成功\n")
+
+
+if __name__ == '__main__':
+    Hot.get_hot_feeds('hot', '6267140', 'dev')
+
+    pass

+ 15 - 0
main/haokan_play.py

@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/23
+
+
+class Play:
+    @classmethod
+    def get_play_feeds(cls, log_type):
+        pass
+
+
+if __name__ == '__main__':
+    Play.get_play_feeds('play')
+
+    pass

+ 261 - 0
main/haokan_publish.py

@@ -0,0 +1,261 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/23
+"""
+上传视频到阿里云 OSS
+上传视频到管理后台
+"""
+import json
+import os
+import shutil
+import time
+import oss2
+import requests
+import urllib3
+from main.common import Common
+proxies = {"http": None, "https": None}
+
+
+class Publish:
+    @classmethod
+    def publish_video_dev(cls, log_type, request_data):
+        """
+        loginUid  站内uid (随机)
+        appType  默认:888888
+        crawlerSrcId   站外视频ID
+        crawlerSrcCode   渠道(自定义 KYK)
+        crawlerSrcPublishTimestamp  视频原发布时间
+        crawlerTaskTimestamp   爬虫创建时间(可以是当前时间)
+        videoPath  视频oss地址
+        coverImgPath  视频封面oss地址
+        title  标题
+        totalTime  视频时长
+        viewStatus  视频的有效状态 默认1
+        versionCode  版本 默认1
+        :return:
+        """
+        # Common.logger(log_type).info('publish request data: {}'.format(request_data))
+        result = cls.request_post('https://videotest.yishihui.com/longvideoapi/crawler/video/send', request_data)
+        # Common.logger(log_type).info('publish result: {}'.format(result))
+        video_id = result["data"]["id"]
+        # Common.logger(log_type).info('video_id: {}'.format(video_id))
+        if result['code'] != 0:
+            Common.logger(log_type).error('pushlish failure msg = {}'.format(result['msg']))
+        else:
+            Common.logger(log_type).info('publish success video_id = : {}'.format(request_data['crawlerSrcId']))
+        return video_id
+
+    @classmethod
+    def publish_video_prod(cls, log_type, request_data):
+        """
+        loginUid  站内uid (随机)
+        appType  默认:888888
+        crawlerSrcId   站外视频ID
+        crawlerSrcCode   渠道(自定义 KYK)
+        crawlerSrcPublishTimestamp  视频原发布时间
+        crawlerTaskTimestamp   爬虫创建时间(可以是当前时间)
+        videoPath  视频oss地址
+        coverImgPath  视频封面oss地址
+        title  标题
+        totalTime  视频时长
+        viewStatus  视频的有效状态 默认1
+        versionCode  版本 默认1
+        :return:
+        """
+        result = cls.request_post('https://longvideoapi.piaoquantv.com/longvideoapi/crawler/video/send', request_data)
+        # Common.logger(log_type).info('publish result: {}'.format(result))
+        video_id = result["data"]["id"]
+        # Common.logger(log_type).info('video_id: {}'.format(video_id))
+        if result['code'] != 0:
+            Common.logger(log_type).error('pushlish failure msg = {}'.format(result['msg']))
+        else:
+            Common.logger(log_type).info('publish success video_id = : {}'.format(request_data['crawlerSrcId']))
+        return video_id
+
+    @classmethod
+    def request_post(cls, request_url, request_data):
+        """
+        post 请求 HTTP接口
+        :param request_url: 接口URL
+        :param request_data: 请求参数
+        :return: res_data json格式
+        """
+        urllib3.disable_warnings()
+        response = requests.post(url=request_url, data=request_data, proxies=proxies, verify=False)
+        if response.status_code == 200:
+            res_data = json.loads(response.text)
+            return res_data
+
+    # 以下代码展示了基本的文件上传、下载、罗列、删除用法。
+
+    # 首先初始化AccessKeyId、AccessKeySecret、Endpoint等信息。
+    # 通过环境变量获取,或者把诸如“<你的AccessKeyId>”替换成真实的AccessKeyId等。
+    #
+    # 以杭州区域为例,Endpoint可以是:
+    #   http://oss-cn-hangzhou.aliyuncs.com
+    #   https://oss-cn-hangzhou.aliyuncs.com
+    # 分别以HTTP、HTTPS协议访问。
+    access_key_id = os.getenv('OSS_TEST_ACCESS_KEY_ID', 'LTAIP6x1l3DXfSxm')
+    access_key_secret = os.getenv('OSS_TEST_ACCESS_KEY_SECRET', 'KbTaM9ars4OX3PMS6Xm7rtxGr1FLon')
+    bucket_name = os.getenv('OSS_TEST_BUCKET', 'art-pubbucket')
+    # endpoint = os.getenv('OSS_TEST_ENDPOINT', 'oss-cn-hangzhou-internal.aliyuncs.com')
+    endpoint = os.getenv('OSS_TEST_ENDPOINT', 'oss-cn-hangzhou.aliyuncs.com')
+
+    # 确认上面的参数都填写正确了
+    for param in (access_key_id, access_key_secret, bucket_name, endpoint):
+        assert '<' not in param, '请设置参数:' + param
+
+    # 创建Bucket对象,所有Object相关的接口都可以通过Bucket对象来进行
+    bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)
+
+    """
+    处理流程:
+    1. 定时(每天凌晨1点执行一次)循环files文件下的内容 结构:files -> 视频文件夹 -> 视频文件 + 封面图 + 基本信息
+    2. 视频文件和封面上传到oss
+    - 视频文件oss目录  longvideo/crawler_local/video/prod/文件名
+    - 视频封面oss目录  longvideo/crawler_local/image/prod/文件名
+    3. 发布视频
+    - 读取 基本信息 调用发布接口
+    """
+    # env 日期20220225 文件名
+    oss_file_path_video = 'longvideo/crawler_local/video/{}/{}/{}'
+    oss_file_path_image = 'longvideo/crawler_local/image/{}/{}/{}'
+
+    @classmethod
+    def put_file(cls, log_type, oss_file, local_file):
+        cls.bucket.put_object_from_file(oss_file, local_file)
+        Common.logger(log_type).info("put oss file = {}, local file = {} success".format(oss_file, local_file))
+
+    # 清除本地文件
+    @classmethod
+    def remove_local_file(cls, log_type, local_file):
+        os.remove(local_file)
+        Common.logger(log_type).info("remove local file = {} success".format(local_file))
+
+    # 清除本地文件夹
+    @classmethod
+    def remove_local_file_dir(cls, log_type, local_file):
+        os.rmdir(local_file)
+        Common.logger(log_type).info("remove local file dir = {} success".format(local_file))
+
+    local_file_path = './videos'
+    video_file = 'video'
+    image_file = 'image'
+    info_file = 'info'
+    uids_dev_up = [6267140]
+    uids_dev_play = [6267141]
+    uids_prod_up = [20631185, 20631186, 20631187, 20631188, 20631189,
+                    20631190, 20631191, 20631192, 20631193]
+    uids_prod_play = [20631196, 20631197, 20631198, 20631199, 20631200, 20631201]
+
+    @classmethod
+    def upload_and_publish(cls, log_type, our_id, env):
+        """
+        上传视频到 oss
+        :param log_type: 选择的 log
+        :param env: 测试环境:dev,正式环境:prod
+        # :param job: 上升榜:up,播放量:play
+        :param our_id: 站内 UID
+        """
+        Common.logger(log_type).info("upload_and_publish starting...")
+        today = time.strftime("%Y%m%d", time.localtime())
+        # videos 目录下的所有视频文件夹
+        files = os.listdir(cls.local_file_path)
+        for f in files:
+            try:
+                # 单个视频文件夹
+                fi_d = os.path.join(cls.local_file_path, f)
+                # 确认为视频文件夹
+                if os.path.isdir(fi_d):
+                    Common.logger(log_type).info('dir = {}'.format(fi_d))
+                    # 列出所有视频文件夹
+                    dir_files = os.listdir(fi_d)
+                    data = {'appType': '888888',
+                            'crawlerSrcCode': 'HAOKAN',
+                            'viewStatus': '1',
+                            'versionCode': '1'}
+                    now_timestamp = int(round(time.time() * 1000))
+                    data['crawlerTaskTimestamp'] = str(now_timestamp)
+                    # global uid
+                    # if env == "dev" and job == "up":
+                    #     uid = str(random.choice(cls.uids_dev_up))
+                    # elif env == "dev" and job == "play":
+                    #     uid = str(random.choice(cls.uids_dev_play))
+                    # elif env == "prod" and job == "up":
+                    #     uid = str(random.choice(cls.uids_prod_up))
+                    # elif env == "prod" and job == "play":
+                    #     uid = str(random.choice(cls.uids_prod_play))
+                    data['loginUid'] = our_id
+                    # 单个视频文件夹下的所有视频文件
+                    for fi in dir_files:
+                        # 视频文件夹下的所有文件路径
+                        fi_path = fi_d + '/' + fi
+                        Common.logger(log_type).info('dir fi_path = {}'.format(fi_path))
+                        # 读取 info.txt,赋值给 data
+                        if cls.info_file in fi:
+                            f = open(fi_path, "r", encoding="UTF-8")
+                            # 读取数据 数据准确性写入的时候保证 读取暂不处理
+                            for i in range(14):
+                                line = f.readline()
+                                line = line.replace('\n', '')
+                                if line is not None and len(line) != 0 and not line.isspace():
+                                    # Common.logger(log_type).info("line = {}".format(line))
+                                    if i == 0:
+                                        data['crawlerSrcId'] = line
+                                    elif i == 1:
+                                        data['title'] = line
+                                    elif i == 2:
+                                        data['totalTime'] = line
+                                    elif i == 8:
+                                        data['crawlerSrcPublishTimestamp'] = line
+                                else:
+                                    Common.logger(log_type).warning("{} line is None".format(fi_path))
+                            f.close()
+                            # remove info.txt
+                            cls.remove_local_file(log_type, fi_path)
+                    # 刷新数据
+                    dir_files = os.listdir(fi_d)
+                    for fi in dir_files:
+                        fi_path = fi_d + '/' + fi
+                        # Common.logger(log_type).info('dir fi_path = {}'.format(fi_path))
+                        # 上传oss
+                        if cls.video_file in fi:
+                            global oss_video_file
+                            if env == "dev":
+                                oss_video_file = cls.oss_file_path_video.format("dev", today, data['crawlerSrcId'])
+                            elif env == "prod":
+                                oss_video_file = cls.oss_file_path_video.format("prod", today, data['crawlerSrcId'])
+                            Common.logger(log_type).info("oss_video_file = {}".format(oss_video_file))
+                            cls.put_file(log_type, oss_video_file, fi_path)
+                            data['videoPath'] = oss_video_file
+                            Common.logger(log_type).info("videoPath = {}".format(oss_video_file))
+                        elif cls.image_file in fi:
+                            global oss_image_file
+                            if env == "dev":
+                                oss_image_file = cls.oss_file_path_image.format("env", today, data['crawlerSrcId'])
+                            elif env == "prod":
+                                oss_image_file = cls.oss_file_path_image.format("prod", today, data['crawlerSrcId'])
+                            Common.logger(log_type).info("oss_image_file = {}".format(oss_image_file))
+                            cls.put_file(log_type, oss_image_file, fi_path)
+                            data['coverImgPath'] = oss_image_file
+                            Common.logger(log_type).info("coverImgPath = {}".format(oss_image_file))
+                        # 全部remove
+                        cls.remove_local_file(log_type, fi_path)
+
+                    # 发布
+                    if env == "dev":
+                        video_id = cls.publish_video_dev(log_type, data)
+                    elif env == "prod":
+                        video_id = cls.publish_video_prod(log_type, data)
+                    else:
+                        video_id = cls.publish_video_dev(log_type, data)
+                    cls.remove_local_file_dir(log_type, fi_d)
+                    Common.logger(log_type).info('video_id:{}', video_id)
+                    return video_id
+
+                else:
+                    Common.logger(log_type).error('file not a dir = {}'.format(fi_d))
+            except Exception as e:
+                # 删除视频文件夹
+                shutil.rmtree("./videos/" + f + "/")
+                Common.logger(log_type).exception('upload_and_publish error', e)

+ 27 - 0
main/run_haokan_hot.py

@@ -0,0 +1,27 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/24
+import datetime
+import os
+import sys
+import time
+sys.path.append(os.getcwd())
+from main.common import Common
+from main.haokan_hot import Hot
+
+
+class Main:
+    @classmethod
+    def main(cls, log_type, our_id, env):
+        while True:
+            if datetime.datetime.now().now().hour >= 12:
+                Hot.get_hot_feeds(log_type, our_id, env)
+                Common.del_logs(log_type)
+                Common.logger(log_type).info(f'进入热榜抓取完毕,休眠{24-datetime.datetime.now().hour}小时')
+                time.sleep(3600*(24-datetime.datetime.now().hour))
+            else:
+                pass
+
+
+if __name__ == '__main__':
+    Main.main('hot', '26117577', 'prod')

+ 3 - 0
videos/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/11/23