Procházet zdrojové kódy

1. 岁岁年年迎福气爬虫

罗俊辉 před 1 rokem
rodič
revize
e98399386a

+ 43 - 109
suisuiniannianyingfuqi/suisuiniannianyingfuqi_recommend/suisuiniannianyingfuqi_recommend_scheduling.py

@@ -3,10 +3,9 @@
 # @Time: 2023/4/13
 import json
 import os
-import shutil
 import sys
 import time
-from hashlib import md5
+import uuid
 import requests
 import urllib3
 from requests.adapters import HTTPAdapter
@@ -14,10 +13,9 @@ from requests.adapters import HTTPAdapter
 from common.mq import MQ
 sys.path.append(os.getcwd())
 from common.common import Common
-from common.feishu import Feishu
-from common.publish import Publish
 from common.public import download_rule
 from common.scheduling_db import MysqlHelper
+from common.aliyun_log import AliyunLogger
 
 
 class SuisuiniannianyingfuqiRecommendScheduling:
@@ -79,6 +77,15 @@ class SuisuiniannianyingfuqiRecommendScheduling:
                     feeds = response.json()['data']['video_list']['data']
                     for i in range(len(feeds)):
                         try:
+                            trace_id = crawler + str(uuid.uuid1())
+                            AliyunLogger.logging(
+                                code="1001",
+                                platform=crawler,
+                                mode=log_type,
+                                env=env,
+                                data=feeds[i],
+                                message="扫描到一条视频"
+                            )
                             publish_time_str = feeds[i].get('createtime', '')
                             publish_time_stamp = int(time.mktime(time.strptime(publish_time_str, "%Y-%m-%d")))
                             video_dict = {'video_title': feeds[i].get('title', "").replace("'", "").replace('"', ''),
@@ -108,6 +115,15 @@ class SuisuiniannianyingfuqiRecommendScheduling:
                             elif cls.repeat_video(log_type, crawler, video_dict["video_id"], env) != 0:
                                 Common.logger(log_type, crawler).info('视频已下载\n')
                                 Common.logging(log_type, crawler, env, '视频已下载\n')
+                                AliyunLogger.logging(
+                                    code="2002",
+                                    platform=crawler,
+                                    mode=log_type,
+                                    message="重复的视频",
+                                    data=video_dict,
+                                    trace_id=trace_id,
+                                    env=env
+                                )
                             else:
                                 video_dict["out_user_id"] = video_dict["user_id"]
                                 video_dict["platform"] = crawler
@@ -119,117 +135,35 @@ class SuisuiniannianyingfuqiRecommendScheduling:
                                 video_dict["user_id"] = our_uid
                                 video_dict["publish_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
                                 mq.send_msg(video_dict)
+                                AliyunLogger.logging(
+                                    code="1002",
+                                    platform=crawler,
+                                    mode=log_type,
+                                    message="成功发送至 ETL",
+                                    data=video_dict,
+                                    trace_id=trace_id,
+                                    env=env
+                                )
                         except Exception as e:
                             Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
                             Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
+                            AliyunLogger.logging(
+                                code="3000",
+                                platform=crawler,
+                                mode=log_type,
+                                message=f"抓取单条视频异常:{e}\n",
+                                env=env
+                            )
             except Exception as e:
                 Common.logger(log_type, crawler).error(f"抓取第{page}页时异常:{e}\n")
                 Common.logging(log_type, crawler, env, f"抓取第{page}页时异常:{e}\n")
-
-    # 下载 / 上传
-    @classmethod
-    def download_publish(cls, log_type, crawler, our_uid, video_dict, rule_dict, env):
-        # 下载视频
-        Common.download_method(log_type=log_type, crawler=crawler, text='video', title=video_dict['video_title'], url=video_dict['video_url'])
-
-        md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
-        try:
-            if os.path.getsize(f"./{crawler}/videos/{md_title}/video.mp4") == 0:
-                # 删除视频文件夹
-                shutil.rmtree(f"./{crawler}/videos/{md_title}")
-                Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
-                return
-        except FileNotFoundError:
-            # 删除视频文件夹
-            shutil.rmtree(f"./{crawler}/videos/{md_title}")
-            Common.logger(log_type, crawler).info("视频文件不存在,删除文件夹成功\n")
-            return
-
-        ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
-        video_dict["duration"] = ffmpeg_dict["duration"]
-        video_dict["video_width"] = ffmpeg_dict["width"]
-        video_dict["video_height"] = ffmpeg_dict["height"]
-
-        # 下载封面
-        Common.download_method(log_type=log_type, crawler=crawler, text='cover', title=video_dict['video_title'], url=video_dict['cover_url'])
-        # 保存视频信息至txt
-        Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
-
-        if env == "dev":
-            oss_endpoint = "out"
-        else:
-            oss_endpoint = "inner"
-        # 上传视频
-        Common.logger(log_type, crawler).info("开始上传视频...")
-        our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                  crawler=crawler,
-                                                  strategy="推荐榜爬虫策略",
-                                                  our_uid=our_uid,
-                                                  env=env,
-                                                  oss_endpoint=oss_endpoint)
-        if env == 'dev':
-            our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
-        else:
-            our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
-        Common.logger(log_type, crawler).info("视频上传完成")
-
-        if our_video_id is None:
-            try:
-                # 删除视频文件夹
-                shutil.rmtree(f"./{crawler}/videos/{md_title}")
-                return
-            except FileNotFoundError:
-                return
-
-        # 视频写入飞书
-        Feishu.insert_columns(log_type, crawler, "290bae", "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['play_cnt'],
-                   video_dict['duration'],
-                   f"{video_dict['video_width']}*{video_dict['video_height']}",
-                   video_dict['cover_url'],
-                   video_dict['video_url']]]
-        time.sleep(0.5)
-        Feishu.update_values(log_type, crawler, "290bae", "F2:Z2", values)
-        Common.logger(log_type, crawler).info(f"视频已保存至云文档\n")
-
-        # 视频信息保存数据库
-        insert_sql = f""" insert into crawler_video(video_id,
-                                                out_user_id,
-                                                platform,
-                                                strategy,
-                                                out_video_id,
-                                                video_title,
-                                                cover_url,
-                                                video_url,
-                                                duration,
-                                                publish_time,
-                                                play_cnt,
-                                                crawler_rule,
-                                                width,
-                                                height)
-                                                values({our_video_id},
-                                                "{video_dict['user_id']}",
-                                                "{cls.platform}",
-                                                "推荐榜爬虫策略",
-                                                "{video_dict['video_id']}",
-                                                "{video_dict['video_title']}",
-                                                "{video_dict['cover_url']}",
-                                                "{video_dict['video_url']}",
-                                                {int(video_dict['duration'])},
-                                                "{video_dict['publish_time_str']}",
-                                                {int(video_dict['play_cnt'])},
-                                                '{json.dumps(rule_dict)}',
-                                                {int(video_dict['video_width'])},
-                                                {int(video_dict['video_height'])}) """
-        Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
-        MysqlHelper.update_values(log_type, crawler, insert_sql, env, action='')
-        Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
+                AliyunLogger.logging(
+                    code="3000",
+                    platform=crawler,
+                    mode=log_type,
+                    message=f"抓取第{page}页时异常:{e}\n",
+                    env=env
+                )
 
 
 if __name__ == '__main__':