wangkun 1 gadu atpakaļ
vecāks
revīzija
f0a23c2c1f

+ 3 - 0
README.MD

@@ -130,6 +130,7 @@ ps aux | grep shipinhao_search | grep -v grep | awk '{print $2}' | xargs kill -9
 /bin/sh /Users/wangkun/Desktop/crawler/piaoquan_crawler/main/process_mq.sh "xng" "xiaoniangao" "play" "dev"
 /bin/sh /Users/wangkun/Desktop/crawler/piaoquan_crawler/main/process_mq.sh "xng" "xiaoniangao" "hour" "dev"
 /bin/sh /Users/wangkun/Desktop/crawler/piaoquan_crawler/main/process_mq.sh "xng" "xiaoniangao" "author" "dev"
+/bin/sh /Users/wangkun/Desktop/crawler/piaoquan_crawler/main/process_mq.sh "kyk" "kanyikan" "recommend" "dev"
 
 102 服务器
 # 调用 MQ 爬虫守护进程
@@ -150,6 +151,7 @@ ps aux | grep shipinhao_search | grep -v grep | awk '{print $2}' | xargs kill -9
 * * * * * /usr/bin/sh /root/piaoquan_crawler/main/process_mq.sh "xng" "xiaoniangao" "play" "prod"
 * * * * * /usr/bin/sh /root/piaoquan_crawler/main/process_mq.sh "xng" "xiaoniangao" "hour" "prod"
 * * * * * /usr/bin/sh /root/piaoquan_crawler/main/process_mq.sh "xng" "xiaoniangao" "author" "prod"
+* * * * * /bin/sh /Users/lieyunye/Desktop/crawler/piaoquan_crawler/process_mq.sh "kyk" "kanyikan" "recommend" "prod"
 
 线下服务器
 
@@ -161,6 +163,7 @@ ps aux | grep xigua | grep -v grep | awk '{print $2}' | xargs kill -9
 ps aux | grep kuaishou | grep -v grep | awk '{print $2}' | xargs kill -9
 ps aux | grep douyin | grep -v grep | awk '{print $2}' | xargs kill -9
 ps aux | grep xiaoniangao | grep -v grep | awk '{print $2}' | xargs kill -9
+ps aux | grep kanyikan | grep -v grep | awk '{print $2}' | xargs kill -9
 ```
 
 #### 生成 requirements.txt

+ 77 - 2
common/common.py

@@ -10,6 +10,7 @@ from loguru import logger
 from hashlib import md5
 import datetime
 import os
+import json
 import time
 import requests
 import ffmpeg
@@ -140,13 +141,87 @@ class Common:
                 os.remove(log_dir + file)
         cls.logger(log_type, crawler).info("清除日志成功\n")
 
+    @classmethod
+    def get_session(cls, log_type, crawler, env):
+        while True:
+            # charles 抓包文件保存目录
+            charles_file_dir = f"./{crawler}/chlsfiles/"
+
+            if int(len(os.listdir(charles_file_dir))) == 1:
+                Common.logger(log_type, crawler).info("未找到chlsfile文件,等待60s")
+                cls.logging(log_type, crawler, env, "未找到chlsfile文件,等待60s")
+                time.sleep(60)
+                continue
+            # 目标文件夹下所有文件
+            all_file = sorted(os.listdir(charles_file_dir))
+            # 获取到目标文件
+            old_file = all_file[-2]
+            # 分离文件名与扩展名
+            new_file = os.path.splitext(old_file)
+            # 重命名文件后缀
+            os.rename(os.path.join(charles_file_dir, old_file),
+                      os.path.join(charles_file_dir, new_file[0] + ".txt"))
+
+            with open(charles_file_dir + new_file[0] + ".txt", encoding='utf-8-sig', errors='ignore') as f:
+                contents = json.load(f, strict=False)
+            if "search.weixin.qq.com" in [text['host'] for text in contents]:
+                for text in contents:
+                    if text["host"] == "search.weixin.qq.com" \
+                            and text["path"] == "/cgi-bin/recwxa/recwxagetunreadmessagecnt":
+                        sessions = text["query"].split("session=")[-1].split("&wxaVersion=")[0]
+                        if "&vid" in sessions:
+                            session = sessions.split("&vid")[0]
+                            return session
+                        elif "&offset" in sessions:
+                            session = sessions.split("&offset")[0]
+                            return session
+                        elif "&wxaVersion" in sessions:
+                            session = sessions.split("&wxaVersion")[0]
+                            return session
+                        elif "&limit" in sessions:
+                            session = sessions.split("&limit")[0]
+                            return session
+                        elif "&scene" in sessions:
+                            session = sessions.split("&scene")[0]
+                            return session
+                        elif "&count" in sessions:
+                            session = sessions.split("&count")[0]
+                            return session
+                        elif "&channelid" in sessions:
+                            session = sessions.split("&channelid")[0]
+                            return session
+                        elif "&subscene" in sessions:
+                            session = sessions.split("&subscene")[0]
+                            return session
+                        elif "&clientVersion" in sessions:
+                            session = sessions.split("&clientVersion")[0]
+                            return session
+                        elif "&sharesearchid" in sessions:
+                            session = sessions.split("&sharesearchid")[0]
+                            return session
+                        elif "&nettype" in sessions:
+                            session = sessions.split("&nettype")[0]
+                            return session
+                        elif "&switchprofile" in sessions:
+                            session = sessions.split("&switchprofile")[0]
+                            return session
+                        elif "&switchnewuser" in sessions:
+                            session = sessions.split("&switchnewuser")[0]
+                            return session
+                        else:
+                            return sessions
+            else:
+                cls.logger(log_type, crawler).info("未找到 session,10s后重新获取")
+                cls.logging(log_type, crawler, env, "未找到 session,10s后重新获取")
+                time.sleep(10)
+
     # 删除 charles 缓存文件,只保留最近的两个文件
     @classmethod
     def del_charles_files(cls, log_type, crawler):
         # 目标文件夹下所有文件
-        all_file = sorted(os.listdir(f"./{crawler}/{crawler}_chlsfiles/"))
+        all_file = sorted(os.listdir(f"./{crawler}/chlsfiles/"))
         for file in all_file[0:-3]:
-            os.remove(f"./{crawler}/{crawler}_chlsfiles/{file}")
+            os.remove(f"./{crawler}/chlsfiles/{file}")
         cls.logger(log_type, crawler).info("删除 charles 缓存文件成功\n")
 
     # 保存视频信息至 "./videos/{video_dict['video_title}/info.txt"

+ 26 - 14
common/publish.py

@@ -176,21 +176,33 @@ class Publish:
         #     uids_dev = [6267140, 6267141]
         #     return random.choice(uids_dev)
 
-        # 小年糕
-        if crawler == 'xiaoniangao' and env == 'prod' and strategy == '定向爬虫策略':
-            uids_prod_xiaoniangao_follow = [50322210, 50322211, 50322212, 50322213, 50322214, 50322215,
-                                            50322216, 50322217, 50322218, 50322219, 50322220, 50322221, 50322236, 50322237]
-            return random.choice(uids_prod_xiaoniangao_follow)
-        elif crawler == 'xiaoniangao' and env == 'prod' and strategy == '小时榜爬虫策略':
-            uids_prod_xiaoniangao_hour = [50322226, 50322227, 50322228, 50322229]
-            return random.choice(uids_prod_xiaoniangao_hour)
-        elif crawler == 'xiaoniangao' and env == 'prod' and strategy == '播放量榜爬虫策略':
-            uids_prod_xiaoniangao_play = [50322222, 50322223, 50322224, 50322225]
-            return random.choice(uids_prod_xiaoniangao_play)
+        if crawler == 'kanyikan' and env == 'prod' and strategy == '推荐抓取策略':
+            uids_prod_kanyikan_recommend = [20631208, 20631209, 20631210, 20631211, 20631212,
+                                        20631213, 20631214, 20631215, 20631216, 20631217,
+                                        20631223, 20631224, 20631225, 20631226, 20631227]
+            return random.choice(uids_prod_kanyikan_recommend)
 
-        elif crawler == 'gongzhonghao' and env == 'prod' and strategy == '定向爬虫策略':
-            uids_prod_gongzhonghao_follow = [26117675, 26117676, 26117677, 26117678, 26117679, 26117680]
-            return random.choice(uids_prod_gongzhonghao_follow)
+        elif crawler == 'kanyikan' and env == 'prod' and strategy == '朋友圈抓取策略':
+            uids_prod_kanyikan_moment = [20631208, 20631209, 20631210, 20631211, 20631212,
+                                         20631213, 20631214, 20631215, 20631216, 20631217,
+                                         20631223, 20631224, 20631225, 20631226, 20631227]
+            return random.choice(uids_prod_kanyikan_moment)
+
+        # # 小年糕
+        # if crawler == 'xiaoniangao' and env == 'prod' and strategy == '定向爬虫策略':
+        #     uids_prod_xiaoniangao_follow = [50322210, 50322211, 50322212, 50322213, 50322214, 50322215,
+        #                                     50322216, 50322217, 50322218, 50322219, 50322220, 50322221, 50322236, 50322237]
+        #     return random.choice(uids_prod_xiaoniangao_follow)
+        # elif crawler == 'xiaoniangao' and env == 'prod' and strategy == '小时榜爬虫策略':
+        #     uids_prod_xiaoniangao_hour = [50322226, 50322227, 50322228, 50322229]
+        #     return random.choice(uids_prod_xiaoniangao_hour)
+        # elif crawler == 'xiaoniangao' and env == 'prod' and strategy == '播放量榜爬虫策略':
+        #     uids_prod_xiaoniangao_play = [50322222, 50322223, 50322224, 50322225]
+        #     return random.choice(uids_prod_xiaoniangao_play)
+        #
+        # elif crawler == 'gongzhonghao' and env == 'prod' and strategy == '定向爬虫策略':
+        #     uids_prod_gongzhonghao_follow = [26117675, 26117676, 26117677, 26117678, 26117679, 26117680]
+        #     return random.choice(uids_prod_gongzhonghao_follow)
         #
         # elif crawler == 'xigua' and env == 'prod' and strategy == '推荐榜爬虫策略':
         #     uids_prod_gongzhonghao_follow = [50322238]

+ 3 - 0
kanyikan/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/21

+ 3 - 0
kanyikan/chlsfiles/__init__.txt

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/21

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
kanyikan/chlsfiles/charles202306211625.txt


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
kanyikan/chlsfiles/charles202306211626.chlsj


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
kanyikan/chlsfiles/charles202306211627.chlsj


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
kanyikan/chlsfiles/charles202306211628.txt


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
kanyikan/chlsfiles/charles202306211629.txt


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
kanyikan/chlsfiles/charles202306211630.chlsj


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
kanyikan/chlsfiles/charles202306211631.chlsj


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
kanyikan/chlsfiles/charles202306211632.chlsj


Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 0 - 0
kanyikan/chlsfiles/charles202306211633.chlsj


+ 3 - 0
kanyikan/kanyikan_main/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/21

+ 111 - 0
kanyikan/kanyikan_main/run_kyk_recommend.py

@@ -0,0 +1,111 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/21
+import argparse
+import random
+from mq_http_sdk.mq_client import *
+from mq_http_sdk.mq_consumer import *
+from mq_http_sdk.mq_exception import MQExceptionBase
+sys.path.append(os.getcwd())
+from common.common import Common
+from common.public import get_consumer, ack_message, task_fun_mq
+from common.scheduling_db import MysqlHelper
+from kanyikan.kanyikan_recommend.kanyikan_recommend import KanyikanRecommend
+
+
+def main(log_type, crawler, topic_name, group_id, env):
+    consumer = get_consumer(topic_name, group_id)
+    # 长轮询表示如果Topic没有消息,则客户端请求会在服务端挂起3秒,3秒内如果有消息可以消费则立即返回响应。
+    # 长轮询时间3秒(最多可设置为30秒)。
+    wait_seconds = 30
+    # 一次最多消费3条(最多可设置为16条)。
+    batch = 1
+    Common.logger(log_type, crawler).info(f'{10 * "="}Consume And Ack Message From Topic{10 * "="}\n'
+                                          f'WaitSeconds:{wait_seconds}\n'
+                                          f'TopicName:{topic_name}\n'
+                                          f'MQConsumer:{group_id}')
+    Common.logging(log_type, crawler, env, f'{10 * "="}Consume And Ack Message From Topic{10 * "="}\n'
+                                           f'WaitSeconds:{wait_seconds}\n'
+                                           f'TopicName:{topic_name}\n'
+                                           f'MQConsumer:{group_id}')
+    while True:
+        try:
+            # 长轮询消费消息。
+            recv_msgs = consumer.consume_message(batch, wait_seconds)
+            for msg in recv_msgs:
+                Common.logger(log_type, crawler).info(f"Receive\n"
+                                                      f"MessageId:{msg.message_id}\n"
+                                                      f"MessageBodyMD5:{msg.message_body_md5}\n"
+                                                      f"MessageTag:{msg.message_tag}\n"
+                                                      f"ConsumedTimes:{msg.consumed_times}\n"
+                                                      f"PublishTime:{msg.publish_time}\n"
+                                                      f"Body:{msg.message_body}\n"
+                                                      f"NextConsumeTime:{msg.next_consume_time}\n"
+                                                      f"ReceiptHandle:{msg.receipt_handle}\n"
+                                                      f"Properties:{msg.properties}")
+                Common.logging(log_type, crawler, env, f"Receive\n"
+                                                       f"MessageId:{msg.message_id}\n"
+                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
+                                                       f"MessageTag:{msg.message_tag}\n"
+                                                       f"ConsumedTimes:{msg.consumed_times}\n"
+                                                       f"PublishTime:{msg.publish_time}\n"
+                                                       f"Body:{msg.message_body}\n"
+                                                       f"NextConsumeTime:{msg.next_consume_time}\n"
+                                                       f"ReceiptHandle:{msg.receipt_handle}\n"
+                                                       f"Properties:{msg.properties}")
+                # ack_mq_message
+                ack_message(log_type=log_type, crawler=crawler, recv_msgs=recv_msgs, consumer=consumer)
+
+                # 处理爬虫业务
+                task_dict = task_fun_mq(msg.message_body)['task_dict']
+                rule_dict = task_fun_mq(msg.message_body)['rule_dict']
+                task_id = task_dict['id']
+                select_user_sql = f"""select * from crawler_user_v3 where task_id={task_id}"""
+                user_list = MysqlHelper.get_values(log_type, crawler, select_user_sql, env, action="")
+                our_uid_list = []
+                for user in user_list:
+                    our_uid_list.append(user["uid"])
+                our_uid = random.choice(our_uid_list)
+                Common.logger(log_type, crawler).info(f"调度任务:{task_dict}")
+                Common.logging(log_type, crawler, env, f"调度任务:{task_dict}")
+                Common.logger(log_type, crawler).info(f"抓取规则:{rule_dict}")
+                Common.logging(log_type, crawler, env, f"抓取规则:{rule_dict}")
+                Common.logger(log_type, crawler).info(f"用户列表:{user_list}\n")
+                Common.logger(log_type, crawler).info(f'开始抓取:{task_dict["taskName"]}\n')
+                Common.logging(log_type, crawler, env, f'开始抓取:{task_dict["taskName"]}\n')
+                KanyikanRecommend.get_videoList(log_type=log_type,
+                                                crawler=crawler,
+                                                rule_dict=rule_dict,
+                                                our_uid=our_uid,
+                                                env=env)
+                Common.del_logs(log_type, crawler)
+                Common.del_charles_files(log_type, crawler)
+                Common.logger(log_type, crawler).info('抓取一轮结束\n')
+                Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+
+        except MQExceptionBase as err:
+            # Topic中没有消息可消费。
+            if err.type == "MessageNotExist":
+                Common.logger(log_type, crawler).info(f"No new message! RequestId:{err.req_id}\n")
+                Common.logging(log_type, crawler, env, f"No new message! RequestId:{err.req_id}\n")
+                continue
+
+            Common.logger(log_type, crawler).info(f"Consume Message Fail! Exception:{err}\n")
+            Common.logging(log_type, crawler, env, f"Consume Message Fail! Exception:{err}\n")
+            time.sleep(2)
+            continue
+
+
+if __name__ == "__main__":
+    parser = argparse.ArgumentParser()  ## 新建参数解释器对象
+    parser.add_argument('--log_type', type=str)  ## 添加参数,注明参数类型
+    parser.add_argument('--crawler')  ## 添加参数
+    parser.add_argument('--topic_name')  ## 添加参数
+    parser.add_argument('--group_id')  ## 添加参数
+    parser.add_argument('--env')  ## 添加参数
+    args = parser.parse_args()  ### 参数赋值,也可以通过终端赋值
+    main(log_type=args.log_type,
+         crawler=args.crawler,
+         topic_name=args.topic_name,
+         group_id=args.group_id,
+         env=args.env)

+ 3 - 0
kanyikan/kanyikan_moment/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/21

+ 443 - 0
kanyikan/kanyikan_moment/kanyikan_moment.py

@@ -0,0 +1,443 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/21
+import os
+import random
+import sys
+import time
+import requests
+import urllib3
+sys.path.append(os.getcwd())
+from main.feishu_lib import Feishu
+from main.common import Common
+from main.publish import Publish
+proxies = {"http": None, "https": None}
+
+
+class Moment:
+    # 过滤词库
+    @classmethod
+    def sensitive_words(cls):
+        word_list = []
+        # 从云文档读取所有敏感词,添加到词库列表
+        lists = Feishu.get_values_batch("moment", "kanyikan", "rofdM5")
+        for i in lists:
+            for j in i:
+                # 过滤空的单元格内容
+                if j is None:
+                    pass
+                else:
+                    word_list.append(j)
+        return word_list
+
+    # 朋友圈视频 ID
+    @classmethod
+    def moment_videoids(cls):
+        try:
+            videoid_list = []
+            # 从云文档读取所有敏感词,添加到词库列表
+            lists = Feishu.get_values_batch("moment", "kanyikan", "iK58HX")
+            for i in lists:
+                for j in i:
+                    # 过滤空的单元格内容
+                    if j is None:
+                        pass
+                    else:
+                        videoid_list.append(j)
+            return videoid_list
+        except Exception as e:
+            Common.logger("moment").error("获取朋友圈视频ID异常:{}", e)
+            return "t3256lo1cmk"
+
+    # 抓取基础规则
+    @staticmethod
+    def download_rule(d_duration, d_width, d_height, d_play_cnt, d_like_cnt, d_share_cnt):
+        """
+        抓取基础规则
+        :param d_duration: 时长
+        :param d_width: 宽
+        :param d_height: 高
+        :param d_play_cnt: 播放量
+        :param d_like_cnt: 点赞量
+        :param d_share_cnt: 分享量
+        :return: 满足规则,返回 True;反之,返回 False
+        """
+        if int(float(d_duration)) >= 40:
+            if int(d_width) >= 0 or int(d_height) >= 0:
+                if int(d_play_cnt) >= 50000:
+                    if int(d_like_cnt) >= 0:
+                        if int(d_share_cnt) >= 0:
+                            return True
+                        else:
+                            return False
+                    else:
+                        return False
+                else:
+                    return False
+            return False
+        return False
+
+    # 获取推荐视频列表
+    @classmethod
+    def get_recommend(cls):
+        url = "https://search.weixin.qq.com/cgi-bin/recwxa/snsgetvideoinfo?"
+        headers = {
+            "content-type": "application/json",
+            "Accept-Encoding": "gzip,compress,br,deflate",
+            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)"
+                          " AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"
+                          " MicroMessenger/8.0.20(0x18001442) NetType/WIFI Language/zh_CN",
+            "Referer": "https://servicewechat.com/wxbb9a805eb4f9533c/236/page-frame.html"
+        }
+        time.sleep(1)
+        videoid = random.choice(cls.moment_videoids())
+        # Common.logger("moment").info("videoid:{}", videoid)
+        params = {
+            "vid": videoid,
+            "openid": "1924336296754305",
+            "model": "iPhone 11<iPhone12,1>14.7.1",
+            "sharesearchid": "8406805193800900989",
+            "shareOpenid": "oh_m45YffSEGxvDH--6s6g9ZkPxg",
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.get(url=url, headers=headers, params=params, proxies=proxies, verify=False)
+            # Common.logger("moment").info("response:{}", r.json())
+            if "rec_video_list" not in r.json()["data"]:
+                Common.logger("moment").warning("该视频无推荐视频列表:{}", videoid)
+            else:
+                feeds = r.json()["data"]["rec_video_list"]
+                for i in range(len(feeds)):
+                    # video_id
+                    if "vid" in feeds[i]:
+                        video_id = feeds[i]["vid"]
+                    else:
+                        video_id = 0
+
+                    # video_title
+                    if "title" in feeds[i]:
+                        video_title = feeds[i]["title"].strip().replace("\n", "") \
+                                .replace("/", "").replace("\\", "").replace("\r", "") \
+                                .replace(":", "").replace("*", "").replace("?", "") \
+                                .replace("?", "").replace('"', "").replace("<", "") \
+                                .replace(">", "").replace("|", "").replace(" ", "") \
+                                .replace("&NBSP", "").replace(".", "。").replace(" ", "") \
+                                .replace("小年糕", "").replace("#", "").replace("Merge", "")
+                    else:
+                        video_title = 0
+
+                    # video_play_cnt
+                    if "played_cnt" in feeds[i]:
+                        video_play_cnt = feeds[i]["played_cnt"]
+                    else:
+                        video_play_cnt = 0
+
+                    # video_comment_cnt
+                    if "comment_cnt" in feeds[i]:
+                        video_comment_cnt = feeds[i]["comment_cnt"]
+                    else:
+                        video_comment_cnt = 0
+
+                    # video_liked_cnt
+                    if "liked_cnt" in feeds[i]:
+                        video_liked_cnt = feeds[i]["liked_cnt"]
+                    else:
+                        video_liked_cnt = 0
+
+                    # video_share_cnt
+                    if "shared_cnt" in feeds[i]:
+                        video_share_cnt = feeds[i]["shared_cnt"]
+                    else:
+                        video_share_cnt = 0
+
+                    # video_duration
+                    if "duration" in feeds[i]:
+                        video_duration = feeds[i]["duration"]
+                    else:
+                        video_duration = 0
+
+                    # video_width / video_height
+                    if "width" in feeds[i] or "height" in feeds[i]:
+                        video_width = feeds[i]["width"]
+                        video_height = feeds[i]["height"]
+                    else:
+                        video_width = 0
+                        video_height = 0
+
+                    # video_send_time
+                    if "upload_time" in feeds[i]:
+                        video_send_time = feeds[i]["upload_time"]
+                    else:
+                        video_send_time = 0
+
+                    # user_name
+                    if "user_info" not in feeds[i]:
+                        user_name = 0
+                    elif "nickname" not in feeds[i]["user_info"]:
+                        user_name = 0
+                    else:
+                        user_name = feeds[i]["user_info"]["nickname"].strip().replace("\n", "")
+
+                    # user_id
+                    if "user_info" not in feeds[i]:
+                        user_id = 0
+                    elif "openid" not in feeds[i]["user_info"]:
+                        user_id = 0
+                    else:
+                        user_id = feeds[i]["user_info"]["openid"]
+
+                    # head_url
+                    if "user_info" not in feeds[i]:
+                        head_url = 0
+                    elif "headimg_url" not in feeds[i]["user_info"]:
+                        head_url = 0
+                    else:
+                        head_url = feeds[i]["user_info"]["headimg_url"]
+
+                    # cover_url
+                    if "cover_url" not in feeds[i]:
+                        cover_url = 0
+                    else:
+                        cover_url = feeds[i]["cover_url"]
+
+                    # video_url
+                    if "play_info" not in feeds[i]:
+                        video_url = 0
+                    elif "items" not in feeds[i]["play_info"]:
+                        video_url = 0
+                    else:
+                        video_url = feeds[i]["play_info"]["items"][-1]["play_url"]
+
+                    Common.logger("moment").info("video_id:{}", video_id)
+                    Common.logger("moment").info("video_title:{}", video_title)
+                    Common.logger("moment").info("user_name:{}", user_name)
+                    Common.logger("moment").info("video_play_cnt:{}", video_play_cnt)
+                    Common.logger("moment").info("video_liked_cnt:{}", video_liked_cnt)
+                    Common.logger("moment").info("video_share_cnt:{}", video_share_cnt)
+                    Common.logger("moment").info("video_duration:{}", video_duration)
+                    Common.logger("moment").info("video_width * video_height:{}*{}", video_width, video_height)
+                    Common.logger("moment").info("video_url:{}", video_url)
+
+                    # 过滤无效视频
+                    if video_id == 0 or video_title == 0 or video_duration == 0 or video_send_time == 0 or user_id == 0\
+                            or head_url == 0 or cover_url == 0 or video_url == 0:
+                        Common.logger("moment").warning("无效视频")
+                    # 抓取基础规则
+                    elif cls.download_rule(
+                            d_duration=video_duration, d_width=video_width, d_height=video_height,
+                            d_play_cnt=video_play_cnt, d_like_cnt=video_liked_cnt,
+                            d_share_cnt=video_share_cnt) is False:
+                        Common.logger("moment").info("不满足基础规则:{}", video_title)
+                    elif int(video_send_time) < 1659283200:
+                        Common.logger("moment").info('发布时间{}<2022-08-01', video_send_time)
+                    # 过滤词库
+                    elif any(word if word in video_title else False for word in cls.sensitive_words()) is True:
+                        Common.logger("moment").info("视频已中过滤词:{}".format(video_title))
+                    # 从已下载视频表去重:https://w42nne6hzg.feishu.cn/sheets/shtcngRPoDYAi24x52j2nDuHMih?sheet=20ce0c
+                    elif video_id in [j for m in Feishu.get_values_batch("moment", "kanyikan", "20ce0c") for j in m]:
+                        Common.logger("moment").info("该视频已下载:{}", video_title)
+                    # 从feeds视频表去重:https://w42nne6hzg.feishu.cn/sheets/shtcngRPoDYAi24x52j2nDuHMih?sheet=tGqZMX
+                    elif video_id in [j for n in Feishu.get_values_batch("moment", "kanyikan", "tGqZMX") for j in n]:
+                        Common.logger("moment").info("该视频已在moment_feeds中:{}", video_title)
+                    else:
+                        Common.logger("moment").info("该视频未下载,添加至moment_feeds中:{}", video_title)
+                        # 看一看+工作表,插入首行
+                        Feishu.insert_columns("moment", "kanyikan", "tGqZMX", "ROWS", 1, 2)
+                        # 获取当前时间
+                        get_feeds_time = int(time.time())
+                        # 准备写入云文档的数据
+                        values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(get_feeds_time)),
+                                   "朋友圈",
+                                   video_id,
+                                   video_title,
+                                   video_play_cnt,
+                                   video_comment_cnt,
+                                   video_liked_cnt,
+                                   video_share_cnt,
+                                   video_duration,
+                                   str(video_width)+"*"+str(video_height),
+                                   time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(video_send_time)),
+                                   user_name,
+                                   user_id,
+                                   head_url,
+                                   cover_url,
+                                   video_url]]
+                        time.sleep(1)
+                        Feishu.update_values("moment", "kanyikan", "tGqZMX", "A2:P2", values)
+
+        except Exception as e:
+            Common.logger("moment").error("获取视频列表异常:{}", e)
+
+    # 下载/上传视频
+    @classmethod
+    def download_publish(cls, env):
+        try:
+            moment_feeds = Feishu.get_values_batch("moment", "kanyikan", "tGqZMX")
+            for i in range(1, len(moment_feeds) + 1):
+                time.sleep(1)
+                # download_push_time = moment_feeds[i][0]
+                download_video_id = moment_feeds[i][2]
+                download_video_title = moment_feeds[i][3]
+                download_video_play_cnt = moment_feeds[i][4]
+                download_video_comment_cnt = moment_feeds[i][5]
+                download_video_like_cnt = moment_feeds[i][6]
+                download_video_share_cnt = moment_feeds[i][7]
+                download_video_duration = moment_feeds[i][8]
+                download_video_resolution = moment_feeds[i][9]
+                download_video_send_time = moment_feeds[i][10]
+                download_user_name = moment_feeds[i][11]
+                download_user_id = moment_feeds[i][12]
+                download_head_url = moment_feeds[i][13]
+                download_cover_url = moment_feeds[i][14]
+                download_video_url = moment_feeds[i][15]
+
+                Common.logger("moment").info("正在判断第{}行,视频:{}", i, download_video_title)
+
+                # 发布时间的时间戳格式(秒为单位)
+                v_send_time = int(time.mktime(time.strptime(download_video_send_time, "%Y/%m/%d %H:%M:%S")))
+                # 抓取时间的时间戳格式(秒为单位)
+                # v_push_time = int(time.mktime(time.strptime(download_push_time, "%Y/%m/%d %H:%M:%S")))
+
+                # 过滤空行及空标题视频
+                if download_video_id is None\
+                        or download_video_id == ""\
+                        or download_video_title is None\
+                        or download_video_title == "":
+                    Common.logger("moment").warning("标题为空或空行,删除")
+                    # 删除行或列,可选 ROWS、COLUMNS
+                    Feishu.dimension_range("moment", "kanyikan", "tGqZMX", "ROWS", i + 1, i + 1)
+                    return
+                # # 视频的抓取时间小于 2 天
+                # elif int(time.time()) - v_push_time > 172800:
+                #     Common.logger("moment").info("抓取时间超过2天:{}", download_video_title)
+                #     # 删除行或列,可选 ROWS、COLUMNS
+                #     Feishu.dimension_range("tGqZMX", "ROWS", i + 1, i + 1)
+                #     return
+                # 视频发布时间不小于 2021-06-01 00:00:00
+                elif v_send_time < 1622476800:
+                    Common.logger("moment").info(
+                        "发布时间小于2021年6月:{},{}", download_video_title, download_video_send_time)
+                    # 删除行或列,可选 ROWS、COLUMNS
+                    Feishu.dimension_range("moment", "kanyikan", "tGqZMX", "ROWS", i + 1, i + 1)
+                    return
+                # 从已下载视频表中去重
+                elif download_video_id in [j for m in Feishu.get_values_batch(
+                        "moment", "kanyikan", "20ce0c") for j in m]:
+                    Common.logger("moment").info("视频已下载:{}", download_video_title)
+                    # 删除行或列,可选 ROWS、COLUMNS
+                    Feishu.dimension_range("moment", "kanyikan", "tGqZMX", "ROWS", i + 1, i + 1)
+                    return
+                # 从已下载视频表中去重
+                elif download_video_id in [j for m in Feishu.get_values_batch(
+                    "moment", "kanyikan", "ho98Ov") for j in m]:
+                    Common.logger("moment").info("视频已下载:{}", download_video_title)
+                    # 删除行或列,可选 ROWS、COLUMNS
+                    Feishu.dimension_range("moment", "kanyikan", "tGqZMX", "ROWS", i + 1, i + 1)
+                    return
+                else:
+                    Common.logger("moment").info("开始下载视频:{}", download_video_title)
+                    # 下载封面
+                    Common.download_method(log_type="moment", text="cover",
+                                           d_name=str(download_video_title), d_url=str(download_cover_url))
+                    # 下载视频
+                    Common.download_method(log_type="moment", text="video",
+                                           d_name=str(download_video_title), d_url=str(download_video_url))
+                    # 保存视频信息至 "./videos/{download_video_title}/info.txt"
+                    with open("./videos/" + download_video_title + "/" + "info.txt",
+                              "a", encoding="UTF-8") as f_a:
+                        f_a.write(str(download_video_id) + "\n" +
+                                  str(download_video_title) + "\n" +
+                                  str(download_video_duration) + "\n" +
+                                  str(download_video_play_cnt) + "\n" +
+                                  str(download_video_comment_cnt) + "\n" +
+                                  str(download_video_like_cnt) + "\n" +
+                                  str(download_video_share_cnt) + "\n" +
+                                  str(download_video_resolution) + "\n" +
+                                  str(int(time.mktime(
+                                      time.strptime(download_video_send_time, "%Y/%m/%d %H:%M:%S")))) + "\n" +
+                                  str(download_user_name) + "\n" +
+                                  str(download_head_url) + "\n" +
+                                  str(download_video_url) + "\n" +
+                                  str(download_cover_url) + "\n" +
+                                  "KANYIKAN_MOMENT")
+                    Common.logger("moment").info("==========视频信息已保存至info.txt==========")
+
+                    # 上传视频
+                    Common.logger("moment").info("开始上传视频:{}".format(download_video_title))
+                    our_video_id = Publish.upload_and_publish(log_type="moment",
+                                                              crawler="kanyikan",
+                                                              strategy="朋友圈抓取策略",
+                                                              our_uid="moment",
+                                                              env=env,
+                                                              oss_endpoint="out")
+                    our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
+                    Common.logger("moment").info("视频上传完成:{}", download_video_title)
+
+                    # 保存视频 ID 到云文档:https://w42nne6hzg.feishu.cn/sheets/shtcngRPoDYAi24x52j2nDuHMih?sheet=20ce0c
+                    Common.logger("moment").info("保存视频ID至云文档:{}", download_video_title)
+                    # 视频ID工作表,插入首行
+                    Feishu.insert_columns("moment", "kanyikan", "20ce0c", "ROWS", 1, 2)
+                    # 视频ID工作表,首行写入数据
+                    upload_time = int(time.time())
+                    values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
+                               "朋友圈",
+                               str(download_video_id),
+                               str(download_video_title),
+                               our_video_link,
+                               download_video_play_cnt,
+                               download_video_comment_cnt,
+                               download_video_like_cnt,
+                               download_video_share_cnt,
+                               download_video_duration,
+                               str(download_video_resolution),
+                               str(download_video_send_time),
+                               str(download_user_name),
+                               str(download_user_id),
+                               str(download_head_url),
+                               str(download_cover_url),
+                               str(download_video_url)]]
+                    time.sleep(1)
+                    Feishu.update_values("moment", "kanyikan", "20ce0c", "F2:W2", values)
+
+                    # 保存视频信息到监控表
+                    Common.logger("moment").info("添加视频到监控表:{}", download_video_title)
+                    # 插入空行
+                    time.sleep(1)
+                    Feishu.insert_columns("moment", "monitor", "6fed97", "ROWS", 1, 2)
+                    # 视频信息写入监控表
+                    values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(int(upload_time))),
+                               str(download_video_id),
+                               download_video_title,
+                               our_video_link,
+                               download_video_duration,
+                               str(download_video_send_time),
+                               download_video_play_cnt]]
+                    time.sleep(1)
+                    Feishu.update_values("moment", "monitor", "6fed97", "F2:L2", values)
+
+                    # 删除行或列,可选 ROWS、COLUMNS
+                    Feishu.dimension_range("moment", "kanyikan", "tGqZMX", "ROWS", i + 1, i + 1)
+                    return
+        except Exception as e:
+            Common.logger("moment").error("下载视频异常:{}", e)
+            # 删除行或列,可选 ROWS、COLUMNS
+            Feishu.dimension_range("moment", "kanyikan", "tGqZMX", "ROWS", 2, 2)
+
+    # 执行下载/上传
+    @classmethod
+    def run_download_publish(cls, env):
+        try:
+            while True:
+                if len(Feishu.get_values_batch("moment", "kanyikan", "tGqZMX")) == 1:
+                    break
+                else:
+                    cls.download_publish(env)
+        except Exception as e:
+            Common.logger("moment").error("执行下载/上传异常:{}", e)
+
+
+if __name__ == "__main__":
+    kuaishou = Moment()
+    kuaishou.run_download_publish("dev")
+
+    pass

+ 3 - 0
kanyikan/kanyikan_recommend/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/21

+ 285 - 0
kanyikan/kanyikan_recommend/kanyikan_recommend.py

@@ -0,0 +1,285 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/21
+import json
+import os
+import random
+import shutil
+import sys
+import time
+from hashlib import md5
+import requests
+import urllib3
+sys.path.append(os.getcwd())
+from common.common import Common
+from common.feishu import Feishu
+from common.publish import Publish
+from common.scheduling_db import MysqlHelper
+from common.public import get_config_from_mysql, download_rule
+proxies = {"http": None, "https": None}
+
+
+class KanyikanRecommend:
+    platform = "看一看"
+
+    @classmethod
+    def repeat_video(cls, log_type, crawler, video_id, env):
+        sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_id}" """
+        repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
+        return len(repeat_video)
+
+    @classmethod
+    def get_videoList(cls, log_type, crawler, our_uid, rule_dict, env):
+        for page in range(1, 101):
+            try:
+                Common.logger(log_type, crawler).info(f"正在抓取第{page}页")
+                Common.logging(log_type, crawler, env, f"正在抓取第{page}页")
+                session = Common.get_session(log_type, crawler, env)
+                if session is None:
+                    time.sleep(1)
+                    continue
+                url = 'https://search.weixin.qq.com/cgi-bin/recwxa/recwxavideolist?'
+                header = {
+                    "Connection": "keep-alive",
+                    "content-type": "application/json",
+                    "Accept-Encoding": "gzip,compress,br,deflate",
+                    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) "
+                                  "AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.18(0x18001236) "
+                                  "NetType/WIFI Language/zh_CN",
+                    "Referer": "https://servicewechat.com/wxbb9a805eb4f9533c/234/page-frame.html",
+                }
+                params = {
+                    'session': session,
+                    "offset": 0,
+                    "wxaVersion": "3.9.2",
+                    "count": "10",
+                    "channelid": "208",
+                    "scene": '310',
+                    "subscene": '1089',
+                    "clientVersion": '8.0.18',
+                    "sharesearchid": '0',
+                    "nettype": 'wifi',
+                    "switchprofile": "0",
+                    "switchnewuser": "0",
+                }
+                urllib3.disable_warnings()
+                response = requests.get(url=url, headers=header, params=params, proxies=proxies, verify=False)
+                if "data" not in response.text:
+                    Common.logger(log_type, crawler).info("获取视频list时,session过期,随机睡眠 31-50 秒")
+                    Common.logging(log_type, crawler, env, "获取视频list时,session过期,随机睡眠 31-50 秒")
+                    # 如果返回空信息,则随机睡眠 31-40 秒
+                    time.sleep(random.randint(31, 40))
+                    continue
+                elif "items" not in response.json()["data"]:
+                    Common.logger(log_type, crawler).info(f"get_feeds:{response.json()},随机睡眠 1-3 分钟")
+                    Common.logging(log_type, crawler, env, f"get_feeds:{response.json()},随机睡眠 1-3 分钟")
+                    # 如果返回空信息,则随机睡眠 1-3 分钟
+                    time.sleep(random.randint(60, 180))
+                    continue
+                feeds = response.json().get("data", {}).get("items", "")
+                if feeds == "":
+                    Common.logger(log_type, crawler).info(f"feeds:{feeds}")
+                    Common.logging(log_type, crawler, env, f"feeds:{feeds}")
+                    time.sleep(random.randint(31, 40))
+                    continue
+                for i in range(len(feeds)):
+                    try:
+                        video_title = feeds[i].get("title", "").strip().replace("\n", "") \
+                            .replace("/", "").replace("\\", "").replace("\r", "") \
+                            .replace(":", "").replace("*", "").replace("?", "") \
+                            .replace("?", "").replace('"', "").replace("<", "") \
+                            .replace(">", "").replace("|", "").replace(" ", "") \
+                            .replace("&NBSP", "").replace(".", "。").replace(" ", "") \
+                            .replace("'", "").replace("#", "").replace("Merge", "")
+                        publish_time_stamp = feeds[i].get("date", 0)
+                        publish_time_str = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(publish_time_stamp))
+                        # 获取播放地址
+                        if "videoInfo" not in feeds[i]:
+                            video_url = ""
+                        elif "mpInfo" in feeds[i]["videoInfo"]["videoCdnInfo"]:
+                            if len(feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"]) > 2:
+                                video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"][2]["url"]
+                            else:
+                                video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"][0]["url"]
+                        elif "ctnInfo" in feeds[i]["videoInfo"]["videoCdnInfo"]:
+                            video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["ctnInfo"]["urlInfo"][0]["url"]
+                        else:
+                            video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["urlInfo"][0]["url"]
+                        video_dict = {
+                            "video_title": video_title,
+                            "video_id": feeds[i].get("videoId", ""),
+                            "play_cnt": feeds[i].get("playCount", 0),
+                            "like_cnt": feeds[i].get("liked_cnt", 0),
+                            "comment_cnt": feeds[i].get("comment_cnt", 0),
+                            "share_cnt": feeds[i].get("shared_cnt", 0),
+                            "duration": feeds[i].get("mediaDuration", 0),
+                            "video_width": feeds[i].get("short_video_info", {}).get("width", 0),
+                            "video_height": feeds[i].get("short_video_info", {}).get("height", 0),
+                            "publish_time_stamp": publish_time_stamp,
+                            "publish_time_str": publish_time_str,
+                            "user_name": feeds[i].get("source", "").strip().replace("\n", ""),
+                            "user_id": feeds[i].get("openid", ""),
+                            "avatar_url": feeds[i].get("bizIcon", ""),
+                            "cover_url": feeds[i].get("thumbUrl", ""),
+                            "video_url": video_url,
+                            "session": session,
+                        }
+                        for k, v in video_dict.items():
+                            Common.logger(log_type, crawler).info(f"{k}:{v}")
+                        Common.logging(log_type, crawler, env, f"video_dict:{video_dict}")
+
+                        if video_dict["video_id"] == "" or video_dict["video_title"] == "" or video_dict["video_url"] == "":
+                            Common.logger(log_type, crawler).info("无效视频\n")
+                            Common.logging(log_type, crawler, env, "无效视频\n")
+                        elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict, rule_dict=rule_dict) is False:
+                            Common.logger(log_type, crawler).info("不满足抓取规则\n")
+                            Common.logging(log_type, crawler, env, "不满足抓取规则\n")
+                        elif any(str(word) if str(word) in video_dict["video_title"] else False
+                                 for word in get_config_from_mysql(log_type=log_type,
+                                                                   source=crawler,
+                                                                   env=env,
+                                                                   text="filter",
+                                                                   action="")) is True:
+                            Common.logger(log_type, crawler).info('已中过滤词\n')
+                            Common.logging(log_type, crawler, env, '已中过滤词\n')
+                        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')
+                        else:
+                            cls.download_publish(log_type=log_type,
+                                                 crawler=crawler,
+                                                 our_uid=our_uid,
+                                                 video_dict=video_dict,
+                                                 rule_dict=rule_dict,
+                                                 env=env)
+                    except Exception as e:
+                        Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
+                        Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
+            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")
+                Common.logging(log_type, crawler, env, "视频size=0,删除成功\n")
+                return
+        except FileNotFoundError:
+            # 删除视频文件夹
+            shutil.rmtree(f"./{crawler}/videos/{md_title}")
+            Common.logger(log_type, crawler).info("视频文件不存在,删除文件夹成功\n")
+            Common.logging(log_type, crawler, env, "视频文件不存在,删除文件夹成功\n")
+            return
+        # 下载封面
+        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)
+
+        # 上传视频
+        Common.logger(log_type, crawler).info("开始上传视频...")
+        Common.logging(log_type, crawler, env, "开始上传视频...")
+        if env == "dev":
+            oss_endpoint = "out"
+            our_video_id = Publish.upload_and_publish(log_type=log_type,
+                                                      crawler=crawler,
+                                                      strategy="推荐抓取策略",
+                                                      our_uid=our_uid,
+                                                      env=env,
+                                                      oss_endpoint=oss_endpoint)
+            our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
+        else:
+            oss_endpoint = "inner"
+            our_video_id = Publish.upload_and_publish(log_type=log_type,
+                                                      crawler=crawler,
+                                                      strategy="推荐抓取策略",
+                                                      our_uid=our_uid,
+                                                      env=env,
+                                                      oss_endpoint=oss_endpoint)
+
+            our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
+
+        if our_video_id is None:
+            try:
+                # 删除视频文件夹
+                shutil.rmtree(f"./{crawler}/videos/{md_title}")
+                return
+            except FileNotFoundError:
+                return
+
+        # 视频信息保存数据库
+        insert_sql = f""" insert into crawler_video(video_id,
+                                                user_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},
+                                                {our_uid},
+                                                "{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}")
+        Common.logging(log_type, crawler, env, f"insert_sql:{insert_sql}")
+        MysqlHelper.update_values(log_type, crawler, insert_sql, env, action="")
+        Common.logger(log_type, crawler).info('视频信息写入数据库成功')
+        Common.logging(log_type, crawler, env, '视频信息写入数据库成功')
+
+        # 保存视频信息到云文档:
+        Feishu.insert_columns(log_type, crawler, "20ce0c", "ROWS", 1, 2)
+        # 看一看+ ,视频ID工作表,首行写入数据
+        values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
+                   "推荐榜",
+                   str(video_dict["video_id"]),
+                   str(video_dict["video_title"]),
+                   our_video_link,
+                   video_dict["play_cnt"],
+                   video_dict["comment_cnt"],
+                   video_dict["like_cnt"],
+                   video_dict["share_cnt"],
+                   video_dict["duration"],
+                   f'{video_dict["video_width"]}*{video_dict["video_height"]}',
+                   video_dict["publish_time_str"],
+                   video_dict["user_name"],
+                   video_dict["user_id"],
+                   video_dict["avatar_url"],
+                   video_dict["cover_url"],
+                   video_dict["video_url"]]]
+        time.sleep(0.5)
+        Feishu.update_values(log_type, crawler, "20ce0c", "F2:Z2", values)
+        Common.logger(log_type, crawler).info("视频信息保存至云文档成功\n")
+        Common.logging(log_type, crawler, env, "视频信息保存至云文档成功\n")
+
+
+if __name__ == "__main__":
+    print(get_config_from_mysql(log_type="recommend",
+                                source="kanyikan",
+                                env="dev",
+                                text="filter",
+                                action=""))
+    pass

+ 3 - 0
kanyikan/logs/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/21

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels