wangkun 1 year ago
parent
commit
e536d00d07
33 changed files with 227 additions and 4324 deletions
  1. 30 8
      benshanzhufu/benshanzhufu_main/run_bszf_recommend.py
  2. 10 10
      benshanzhufu/benshanzhufu_recommend/benshanzhufu_recommend_scheduling.py
  3. 6 1
      common/common.py
  4. 32 18
      dev/dev_script/get_cpu_mem.py
  5. 6 1
      douyin/douyin_main/run_dy_author.py
  6. 7 2
      douyin/douyin_main/run_dy_recommend.py
  7. 9 1
      ganggangdouchuan/ganggangdouchuan_main/run_ganggangdouchuan_recommend.py
  8. 36 11
      ganggangdouchuan/ganggangdouchuan_recommend/ganggangdouchuan_recommend.py
  9. 0 525
      gongzhonghao/gongzhonghao_author/gongzhonghao1_author.py
  10. 0 521
      gongzhonghao/gongzhonghao_author/gongzhonghao2_author.py
  11. 0 522
      gongzhonghao/gongzhonghao_author/gongzhonghao3_author.py
  12. 0 522
      gongzhonghao/gongzhonghao_author/gongzhonghao4_author.py
  13. 0 525
      gongzhonghao/gongzhonghao_author/gongzhonghao5_author.py
  14. 0 0
      gongzhonghao/gongzhonghao_author/gongzhonghao_author_create_user.py
  15. 0 519
      gongzhonghao/gongzhonghao_follow/gongzhonghao_follow_2.py
  16. 0 547
      gongzhonghao/gongzhonghao_follow/gongzhonghao_follow_3.py
  17. 0 108
      gongzhonghao/gongzhonghao_main/run_gzh1_author.py
  18. 0 32
      gongzhonghao/gongzhonghao_main/run_gzh1_author_dev.py
  19. 0 108
      gongzhonghao/gongzhonghao_main/run_gzh2_author.py
  20. 0 110
      gongzhonghao/gongzhonghao_main/run_gzh3_author.py
  21. 0 108
      gongzhonghao/gongzhonghao_main/run_gzh4_author.py
  22. 0 108
      gongzhonghao/gongzhonghao_main/run_gzh5_author.py
  23. 6 1
      gongzhonghao/gongzhonghao_main/run_gzh_author.py
  24. 6 1
      kuaishou/kuaishou_main/run_ks_author.py
  25. 6 1
      kuaishou/kuaishou_main/run_ks_recommend.py
  26. 28 1
      suisuiniannianyingfuqi/suisuiniannianyingfuqi_main/run_ssnnyfq_recommend.py
  27. 9 7
      suisuiniannianyingfuqi/suisuiniannianyingfuqi_recommend/suisuiniannianyingfuqi_recommend_scheduling.py
  28. 6 1
      xiaoniangao/xiaoniangao_main/run_xng_author.py
  29. 8 1
      xiaoniangao/xiaoniangao_main/run_xng_hour.py
  30. 6 2
      xiaoniangao/xiaoniangao_main/run_xng_play.py
  31. 5 0
      xigua/xigua_main/run_xg_author.py
  32. 5 1
      xigua/xigua_main/run_xg_recommend.py
  33. 6 1
      xigua/xigua_main/run_xg_search.py

+ 30 - 8
benshanzhufu/benshanzhufu_main/run_bszf_recommend.py

@@ -24,6 +24,10 @@ def main(log_type, crawler, topic_name, group_id, env):
                                           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:
             # 长轮询消费消息。
@@ -40,6 +44,16 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                       f"NextConsumeTime:{msg.next_consume_time}\n"
                                                       f"ReceiptHandle:{msg.receipt_handle}\n"
                                                       f"Properties:{msg.properties}")
+                Common.logging(logging, 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)
 
@@ -54,9 +68,13 @@ def main(log_type, crawler, topic_name, group_id, env):
                     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.logging(log_type, crawler, env, 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')
                 BenshanzhufuRecommend.get_videoList(log_type=log_type,
                                                     crawler=crawler,
                                                     our_uid=our_uid,
@@ -64,6 +82,7 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                     env=env)
                 # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束')
+                Common.logging(log_type, crawler, env, '抓取一轮结束')
                 benshanzhufu_end_time = int(time.time())
                 benshanzhufu_duration = benshanzhufu_end_time - benshanzhufu_start_time
                 Common.logger(log_type, crawler).info(f"duration {benshanzhufu_duration}\n")
@@ -73,22 +92,25 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 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()  ### 参数赋值,也可以通过终端赋值
+    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)
+         env=args.env)

+ 10 - 10
benshanzhufu/benshanzhufu_recommend/benshanzhufu_recommend_scheduling.py

@@ -13,9 +13,8 @@ from hashlib import md5
 from urllib import parse
 import requests
 import urllib3
-
-from common.mq import MQ
 sys.path.append(os.getcwd())
+from common.mq import MQ
 from common.common import Common
 from common.scheduling_db import MysqlHelper
 from common.feishu import Feishu
@@ -29,7 +28,6 @@ class BenshanzhufuRecommend:
 
     @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}"; """
         sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{video_id}"; """
         repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
         return len(repeat_video)
@@ -64,15 +62,19 @@ class BenshanzhufuRecommend:
             r = requests.get(headers=header, url=url, proxies=proxies, verify=False)
             if r.status_code != 200:
                 Common.logger(log_type, crawler).warning(f"get_videoList:{r.status_code}, {r.text}\n")
+                Common.logging(log_type, crawler, env, f"get_videoList:{r.status_code}, {r.text}\n")
                 return
             elif r.json()['message'] != "list success":
                 Common.logger(log_type, crawler).warning(f"get_videoList:{r.status_code}, {r.json()}\n")
+                Common.logging(log_type, crawler, env, f"get_videoList:{r.status_code}, {r.text}\n")
                 return
             elif "data" not in r.json():
                 Common.logger(log_type, crawler).warning(f"get_videoList:{r.status_code}, {r.json()}\n")
+                Common.logging(log_type, crawler, env, f"get_videoList:{r.status_code}, {r.text}\n")
                 return
             elif len(r.json()['data']["list"]) == 0:
                 Common.logger(log_type, crawler).info(f"没有更多数据了~ {r.json()}\n")
+                Common.logging(log_type, crawler, env, f"没有更多数据了~ {r.json()}\n")
                 return
             else:
                 # 翻页
@@ -105,12 +107,15 @@ class BenshanzhufuRecommend:
                     }
                     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["cover_url"] == "" 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,
@@ -118,15 +123,11 @@ class BenshanzhufuRecommend:
                                                                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)
                         video_dict["out_user_id"] = video_dict["user_id"]
                         video_dict["platform"] = crawler
                         video_dict["strategy"] = log_type
@@ -138,7 +139,6 @@ class BenshanzhufuRecommend:
                         video_dict["publish_time"] = video_dict["publish_time_str"]
                         video_dict["fans_cnt"] = 0
                         video_dict["videos_cnt"] = 0
-
                         mq.send_msg(video_dict)
 
                         # except Exception as e:

+ 6 - 1
common/common.py

@@ -85,7 +85,12 @@ class Common:
             project = 'crawler-log-prod'
             logstore = 'crawler-log-prod'
             endpoint = 'cn-hangzhou.log.aliyuncs.com'
-        elif crawler == "shipinhao" or crawler == "kanyikan":
+        elif crawler == "shipinhao"\
+            or crawler == "kanyikan"\
+            or crawler == "ganggangdouchuan"\
+            or crawler == "zhiqingtiantiankan"\
+            or crawler == "jixiangxingfu"\
+            or crawler == "zhongmiaoyinxin":
             project = 'crawler-log-prod'
             logstore = 'crawler-log-prod'
             endpoint = 'cn-hangzhou.log.aliyuncs.com'

+ 32 - 18
dev/dev_script/get_cpu_mem.py

@@ -1,10 +1,24 @@
 # -*- coding: utf-8 -*-
 # @Author: wangkun
 # @Time: 2023/7/19
+import socket
 import psutil
 
 
 class GetCpuMen:
+    @classmethod
+    def get_ip_address(cls):
+        try:
+            # 创建一个 UDP 套接字
+            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+            # 连接到一个外部 IP 地址
+            sock.connect(("8.8.8.8", 80))
+            # 获取本地 IP 地址
+            local_ip = sock.getsockname()[0]
+            return local_ip
+        except socket.error:
+            return "无法获取本机 IP 地址"
+
     @classmethod
     def get_pid(cls, script):
         # 遍历所有正在运行的进程
@@ -15,6 +29,7 @@ class GetCpuMen:
                 # 检查命令行参数是否包含爬虫脚本的名称或关键字
                 for cmd in cmds:
                     if script in cmd:
+
                         print(f"cmd:{cmd}")
                         # 获取进程的PID
                         pid = proc.pid
@@ -40,22 +55,20 @@ class GetCpuMen:
 
     @classmethod
     def get_all_cpu_mem(cls):
-        script_list = [
-            "run_xg_search",
-            "run_xg_author",
-            "run_xng_author",
-            "run_xng_play",
-            "run_xng_hour",
-            "run_dy_author",
-            "run_dy_recommend",
-            "run_ks_recommend",
-            "run_ks_author",
-            "run_bszf_recommend",
-            "run_ssnnyfq_recommend",
-            "run_gzh_author",
-            "run_weixinzhishu_score",
-            "get_cpu_mem",
-        ]
+        script_list = ["run_xg_search",
+                       "run_xg_author",
+                       "run_xng_author",
+                       "run_xng_play",
+                       "run_xng_hour",
+                       "run_dy_author",
+                       "run_dy_recommend",
+                       "run_ks_recommend",
+                       "run_ks_author",
+                       "run_bszf_recommend",
+                       "run_ssnnyfq_recommend",
+                       "run_gzh_author",
+                       "run_weixinzhishu_score",
+                       "get_cpu_mem"]
 
         for scrip in script_list:
             print(f"scrip:{scrip}")
@@ -65,6 +78,7 @@ class GetCpuMen:
 
 if __name__ == "__main__":
     # GetCpuMen.get_cpu_mem("get_cpu_mem")
-    GetCpuMen.get_all_cpu_mem()
+    # GetCpuMen.get_all_cpu_mem()
+    print(GetCpuMen.get_ip_address())
 
-    pass
+    pass

+ 6 - 1
douyin/douyin_main/run_dy_author.py

@@ -32,6 +32,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                dy_author_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -73,9 +74,13 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                          rule_dict=rule_dict,
                                                          user_list=user_list,
                                                          env=env)
-                Common.del_logs(log_type, crawler)
+                # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+                dy_author_end_time = int(time.time())
+                dy_author_duration = dy_author_start_time - dy_author_end_time
+                Common.logger(log_type, crawler).info(f"duration {dy_author_duration}")
+                Common.logging(logging, crawler, env, f"duration {dy_author_duration}")
 
         except MQExceptionBase as err:
             # Topic中没有消息可消费。

+ 7 - 2
douyin/douyin_main/run_dy_recommend.py

@@ -33,6 +33,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                dy_recommend_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -78,12 +79,16 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                         rule_dict=rule_dict,
                                                         our_uid=our_uid,
                                                         env=env)
-                Common.del_logs(log_type, crawler)
+                # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+                dy_recommend_end_time = int(time.time())
+                dy_recommend_duration = dy_recommend_start_time - dy_recommend_end_time
+                Common.logger(log_type, crawler).info(f"duration {dy_recommend_duration}")
+                Common.logging(log_type, crawler, env, f"duration {dy_recommend_duration}")
 
         except MQExceptionBase as err:
-            # Topic中没有消息可消费。
+            # Topic中没有消息可消费。ew
             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")

+ 9 - 1
ganggangdouchuan/ganggangdouchuan_main/run_ganggangdouchuan_recommend.py

@@ -4,6 +4,7 @@
 import argparse
 import os
 import sys
+import time
 sys.path.append(os.getcwd())
 from common.common import Common
 from ganggangdouchuan.ganggangdouchuan_recommend.ganggangdouchuan_recommend import GanggangdouchuanRecommend
@@ -12,9 +13,16 @@ from ganggangdouchuan.ganggangdouchuan_recommend.ganggangdouchuan_recommend impo
 def main(log_type, crawler, env):
     oss_endpoint = "out"
     Common.logger(log_type, crawler).info('开始抓取:刚刚都传小程序\n')
+    Common.logging(log_type, crawler, env, '开始抓取:刚刚都传小程序\n')
+    ganggangdouchuan_start_time = int(time.time())
     GanggangdouchuanRecommend.start_wechat(log_type, crawler, oss_endpoint, env)
-    Common.del_logs(log_type, crawler)
+    # Common.del_logs(log_type, crawler)
     Common.logger(log_type, crawler).info('抓取完一轮\n')
+    Common.logging(log_type, crawler, env, '抓取完一轮\n')
+    ganggangdouchuan_end_time = int(time.time())
+    ganggangdouchuan_duration = ganggangdouchuan_end_time - ganggangdouchuan_start_time
+    Common.logger(log_type, crawler).info(f"duration {ganggangdouchuan_duration}")
+    Common.logging(log_type, crawler, env, f"duration {ganggangdouchuan_duration}")
 
 
 if __name__ == "__main__":

+ 36 - 11
ganggangdouchuan/ganggangdouchuan_recommend/ganggangdouchuan_recommend.py

@@ -12,7 +12,6 @@ from appium.webdriver.extensions.android.nativekey import AndroidKey
 from appium.webdriver.webdriver import WebDriver
 from selenium.common import NoSuchElementException
 from selenium.webdriver.common.by import By
-
 sys.path.append(os.getcwd())
 from common.common import Common
 from common.feishu import Feishu
@@ -33,6 +32,7 @@ class GanggangdouchuanRecommend:
                 chromedriverExecutable = '/Users/piaoquan/Downloads/chromedriver'
 
             Common.logger(log_type, crawler).info('启动微信')
+            Common.logging(log_type, crawler, env, '启动微信')
             caps = {
                 "platformName": "Android",  # 手机操作系统 Android / iOS
                 "deviceName": "a0a65126",  # 连接的设备名(模拟器或真机),安卓可以随便写
@@ -67,28 +67,33 @@ class GanggangdouchuanRecommend:
                     # 发现并关闭系统菜单栏
                     elif driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view'):
                         Common.logger(log_type, crawler).info('发现并关闭系统下拉菜单栏')
+                        Common.logging(log_type, crawler, env, '发现并关闭系统下拉菜单栏')
                         driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view').click()
                     else:
                         pass
                 except NoSuchElementException:
                     time.sleep(1)
             Common.logger(log_type, crawler).info('下滑,展示小程序选择面板')
+            Common.logging(log_type, crawler, env, '下滑,展示小程序选择面板')
             size = driver.get_window_size()
             driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2),
                          int(size['width'] * 0.5), int(size['height'] * 0.8), 200)
             # 打开小程序"刚刚都传"
             time.sleep(3)
             Common.logger(log_type, crawler).info('打开小程序"刚刚都传"')
+            Common.logging(log_type, crawler, env, '打开小程序"刚刚都传"')
             driver.find_elements(By.XPATH, '//*[@text="刚刚都传"]')[-1].click()
             time.sleep(10)
             cls.get_videoList(log_type, crawler, oss_endpoint, env, driver)
             driver.quit()
             Common.logger(log_type, crawler).info('退出微信成功\n')
+            Common.logging(log_type, crawler, env, '退出微信成功\n')
         except Exception as e:
             Common.logger(log_type, crawler).error(f'start_wechat异常:{e}\n')
+            Common.logging(log_type, crawler, env, f'start_wechat异常:{e}\n')
 
     @classmethod
-    def get_video_url(cls, log_type, crawler, driver: WebDriver, video_element):
+    def get_video_url(cls, log_type, crawler, env, driver: WebDriver, video_element):
         try:
             time.sleep(1)
             # Common.logger(log_type, crawler).info('进入视频详情')
@@ -109,10 +114,11 @@ class GanggangdouchuanRecommend:
                     time.sleep(1)
         except Exception as e:
             Common.logger(log_type, crawler).error(f'get_video_url异常:{e}\n')
+            Common.logging(log_type, crawler, env, f'get_video_url异常:{e}\n')
 
     # 切换 Handle
     @classmethod
-    def search_elements(cls, log_type, crawler, driver: WebDriver, xpath):
+    def search_elements(cls, log_type, crawler, env, driver: WebDriver, xpath):
         try:
             windowHandles = driver.window_handles
             # Common.logger(log_type, crawler).info('windowHandles:{}', windowHandles)
@@ -129,12 +135,14 @@ class GanggangdouchuanRecommend:
                     pass
         except Exception as e:
             Common.logger(log_type, crawler).warning(f'search_elements异常:{e}\n')
+            Common.logging(log_type, crawler, env, f'search_elements异常:{e}\n')
 
     @classmethod
-    def check_to_applet(cls, log_type, crawler, driver: WebDriver):
+    def check_to_applet(cls, log_type, crawler, env, driver: WebDriver):
         while True:
             webview = driver.contexts
             Common.logger(log_type, crawler).info(f"webviews:{webview}")
+            Common.logging(log_type, crawler, env, f"webviews:{webview}")
             driver.switch_to.context(webview[1])
             windowHandles = driver.window_handles
             for handle in windowHandles:
@@ -144,55 +152,64 @@ class GanggangdouchuanRecommend:
                     video_list = driver.find_element(By.XPATH, '//wx-view[text()="视频"]')
                     video_list.click()
                     Common.logger(log_type, crawler).info('切换到小程序视频列表成功\n')
+                    Common.logging(log_type, crawler, env, '切换到小程序视频列表成功\n')
                     return
                 except NoSuchElementException:
                     time.sleep(1)
             Common.logger(log_type, crawler).info("切换到小程序失败\n")
+            Common.logging(log_type, crawler, env, "切换到小程序失败\n")
             break
 
     @classmethod
     def repeat_out_video_id(cls, log_type, crawler, out_video_id, env):
-        sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{out_video_id}"; """
+        sql = f""" select * from crawler_video where platform in ("{crawler}", "{cls.platform}") and out_video_id="{out_video_id}"; """
         repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
         return len(repeat_video)
 
     @classmethod
     def repeat_video_url(cls, log_type, crawler, video_url, env):
-        sql = f""" select * from crawler_video where platform="{cls.platform}" and video_url="{video_url}"; """
+        # sql = f""" select * from crawler_video where platform="{cls.platform}" and video_url="{video_url}"; """
+        sql = f""" select * from crawler_video where platform in ("{cls.platform}", "{crawler}") and video_url="{video_url}"; """
         repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
         return len(repeat_video)
 
     @classmethod
     def get_videoList(cls, log_type, crawler, oss_endpoint, env, driver: WebDriver):
         # 切换到小程序
-        cls.check_to_applet(log_type, crawler, driver)
+        cls.check_to_applet(log_type, crawler, env, driver)
         time.sleep(1)
         index = 0
 
         while True:
             try:
-                if cls.search_elements(log_type, crawler, driver, '//wx-view[@class="lists"]') is None:
+                if cls.search_elements(log_type, crawler, env, driver, '//wx-view[@class="lists"]') is None:
                     Common.logger(log_type, crawler).info('窗口已销毁\n')
+                    Common.logging(log_type, crawler, env, '窗口已销毁\n')
                     return
 
                 Common.logger(log_type, crawler).info('获取视频列表\n')
-                video_elements = cls.search_elements(log_type, crawler, driver, '//wx-view[@class="list"]')
+                Common.logging(log_type, crawler, env, '获取视频列表\n')
+                video_elements = cls.search_elements(log_type, crawler, env, driver, '//wx-view[@class="list"]')
                 if video_elements is None:
                     Common.logger(log_type, crawler).warning(f'video_elements:{video_elements}')
+                    Common.logging(log_type, crawler, env, f'video_elements:{video_elements}')
                     return
 
                 video_element_temp = video_elements[index:]
                 if len(video_element_temp) == 0:
                     Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
+                    Common.logging(log_type, crawler, env, '到底啦~~~~~~~~~~~~~\n')
                     return
 
                 for i, video_element in enumerate(video_element_temp):
                     if video_element is None:
                         Common.logger(log_type, crawler).info('到底啦~\n')
+                        Common.logging(log_type, crawler, env, '到底啦~\n')
                         return
                     cls.i += 1
-                    cls.search_elements(log_type, crawler, driver, '//wx-view[@class="list"]')
+                    cls.search_elements(log_type, crawler, env, driver, '//wx-view[@class="list"]')
                     Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
+                    Common.logging(log_type, crawler, env, f'拖动"视频"列表第{cls.i}个至屏幕中间')
                     time.sleep(3)
                     driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})", video_element)
 
@@ -220,29 +237,37 @@ class GanggangdouchuanRecommend:
                     }
                     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_title is None or cover_url is None:
                         Common.logger(log_type, crawler).info("无效视频\n")
+                        Common.logging(log_type, crawler, env, "无效视频\n")
                     elif cls.repeat_out_video_id(log_type, crawler, out_video_id, env) != 0:
                         Common.logger(log_type, crawler).info('视频已下载\n')
+                        Common.logging(log_type, crawler, env, '视频已下载\n')
                     else:
-                        video_url = cls.get_video_url(log_type, crawler, driver, video_element)
+                        video_url = cls.get_video_url(log_type, crawler, env, driver, video_element)
                         Common.logger(log_type, crawler).info(f'video_url:{video_url}')
+                        Common.logging(log_type, crawler, env, f'video_url:{video_url}')
                         if video_url is None:
                             Common.logger(log_type, crawler).info("未获取到视频播放地址\n")
+                            Common.logging(log_type, crawler, env, "未获取到视频播放地址\n")
                             driver.press_keycode(AndroidKey.BACK)
                         elif cls.repeat_video_url(log_type, crawler, video_url, env) != 0:
                             Common.logger(log_type, crawler).info('视频已下载\n')
+                            Common.logging(log_type, crawler, env, '视频已下载\n')
                             driver.press_keycode(AndroidKey.BACK)
                         else:
                             video_dict["video_url"]=video_url
                             cls.download_publish(log_type, crawler, video_dict, oss_endpoint, env, driver)
                 Common.logger(log_type, crawler).info('已抓取完一组视频,休眠10秒\n')
+                Common.logging(log_type, crawler, env, '已抓取完一组视频,休眠10秒\n')
                 time.sleep(10)
                 index = index + len(video_element_temp)
 
             except Exception as e:
                 Common.logger(log_type, crawler).error(f'get_videoList异常:{e}\n')
+                Common.logging(log_type, crawler, env, f'get_videoList异常:{e}\n')
                 cls.i = 0
                 return
 

+ 0 - 525
gongzhonghao/gongzhonghao_author/gongzhonghao1_author.py

@@ -1,525 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/3/28
-import datetime
-import json
-import os
-import random
-import shutil
-import sys
-import time
-from hashlib import md5
-import requests
-import urllib3
-from selenium.webdriver import DesiredCapabilities
-from selenium.webdriver.chrome.service import Service
-from selenium.webdriver.common.by import By
-from selenium import webdriver
-
-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.getuser import getUser
-from common.scheduling_db import MysqlHelper
-from common.public import get_config_from_mysql, download_rule, title_like
-
-
-class GongzhonghaoAuthor1:
-    platform = "公众号"
-
-    # 获取 token
-    @classmethod
-    def get_token(cls, log_type, crawler, env):
-        select_sql = f""" select * from crawler_config where source="{crawler}" and title LIKE "%公众号_1%";"""
-        configs = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
-        if len(configs) == 0:
-            Feishu.bot(log_type, crawler, "公众号_1:未配置token")
-            time.sleep(60)
-            return None
-        token_dict = {
-            "token_id": configs[0]["id"],
-            "title": configs[0]["title"].strip(),
-            "token": dict(eval(configs[0]["config"]))["token"].strip(),
-            "cookie": dict(eval(configs[0]["config"]))["cookie"].strip(),
-            "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(configs[0]["update_time"]/1000))),
-            "operator": configs[0]["operator"].strip()
-        }
-        # for k, v in token_dict.items():
-        #     print(f"{k}:{type(v)}, {v}")
-        return token_dict
-
-    @classmethod
-    def get_users(cls, log_type, crawler, user_sheet, sheetid, i, env):
-        user_name = user_sheet[i][0]
-        wechat_name = user_sheet[i][2]
-        if wechat_name is None or wechat_name.strip() == "" or wechat_name.replace(" ", "") == "":
-            wechat_name = user_name
-        out_uid = user_sheet[i][3]
-        avatar_url = user_sheet[i][4]
-        if out_uid is None or out_uid.strip() == "" or out_uid.replace(" ", "") == "":
-            user_info_dict = cls.get_user_info(log_type=log_type, crawler=crawler, wechat_name=wechat_name, env=env)
-            out_uid = user_info_dict["user_id"]
-            avatar_url = user_info_dict["avatar_url"]
-            Feishu.update_values(log_type, crawler, sheetid, f'D{i + 1}:E{i + 1}', [[out_uid, avatar_url]])
-
-        our_user_dict = {
-            'user_name': user_name,
-            'user_id': out_uid,
-            'wechat_name': wechat_name,
-            'avatar_url': avatar_url,
-        }
-        for k, v in our_user_dict.items():
-            Common.logger(log_type, crawler).info(f"{k}:{v}")
-        Common.logging(log_type, crawler, env, f'our_user_dict:{our_user_dict}')
-        return our_user_dict
-
-    # 获取用户 fakeid
-    @classmethod
-    def get_user_info(cls, log_type, crawler, wechat_name, env):
-        Common.logger(log_type, crawler).info(f"获取站外用户信息:{wechat_name}")
-        Common.logging(log_type, crawler, env, f"获取站外用户信息:{wechat_name}")
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=1011071554&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "search_biz",
-                "begin": "0",
-                "count": "5",
-                "query": str(wechat_name),
-                "token": token_dict['token'],
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if "list" not in r.json() or len(r.json()["list"]) == 0:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            user_info_dict = {'user_name': r.json()["list"][0]["nickname"],
-                              'user_id': r.json()["list"][0]["fakeid"],
-                              'avatar_url': r.json()["list"][0]["round_head_img"]}
-            return user_info_dict
-
-    # 获取腾讯视频下载链接
-    @classmethod
-    def get_tencent_video_url(cls, video_id):
-        url = 'https://vv.video.qq.com/getinfo?vids=' + str(video_id) + '&platform=101001&charge=0&otype=json'
-        response = requests.get(url=url).text.replace('QZOutputJson=', '').replace('"};', '"}')
-        response = json.loads(response)
-        url = response['vl']['vi'][0]['ul']['ui'][0]['url']
-        fvkey = response['vl']['vi'][0]['fvkey']
-        video_url = url + str(video_id) + '.mp4?vkey=' + fvkey
-        return video_url
-
-    @classmethod
-    def get_video_url(cls, article_url, env):
-        # 打印请求配置
-        ca = DesiredCapabilities.CHROME
-        ca["goog:loggingPrefs"] = {"performance": "ALL"}
-
-        # 不打开浏览器运行
-        chrome_options = webdriver.ChromeOptions()
-        chrome_options.add_argument("headless")
-        chrome_options.add_argument(
-            f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36')
-        chrome_options.add_argument("--no-sandbox")
-
-        # driver初始化
-        if env == "prod":
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
-        else:
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service(
-                '/Users/wangkun/Downloads/chromedriver/chromedriver_v113/chromedriver'))
-
-        driver.implicitly_wait(10)
-        driver.get(article_url)
-        time.sleep(1)
-
-        if len(driver.find_elements(By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]')) != 0:
-            video_url = driver.find_element(
-                By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]').get_attribute('src')
-        elif len(driver.find_elements(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]')) != 0:
-            iframe = driver.find_element(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]').get_attribute(
-                'src')
-            video_id = iframe.split('vid=')[-1].split('&')[0]
-            video_url = cls.get_tencent_video_url(video_id)
-        else:
-            video_url = 0
-        driver.quit()
-        return video_url
-
-    # 获取文章列表
-    @classmethod
-    def get_videoList(cls, log_type, crawler, rule_dict, user_dict, env):
-        mq = MQ(topic_name="topic_crawler_etl_" + env)
-        begin = 0
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=" + str(token_dict['token']) + "&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "list_ex",
-                "begin": str(begin),
-                "count": "5",
-                "fakeid": user_dict['user_id'],
-                "type": "9",
-                "query": "",
-                "token": str(token_dict['token']),
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "invalid args" and r.json()["base_resp"]["ret"] == 200002:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"公众号:{user_dict['user_name']}\n抓取异常, 请检查该公众号\n")
-                return
-            if 'app_msg_list' not in r.json():
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if len(r.json()['app_msg_list']) == 0:
-                Common.logger(log_type, crawler).info('没有更多视频了\n')
-                Common.logging(log_type, crawler, env, '没有更多视频了\n')
-                return
-            else:
-                begin += 5
-                app_msg_list = r.json()['app_msg_list']
-                for article in app_msg_list:
-                    try:
-                        create_time = article.get('create_time', 0)
-                        publish_time_stamp = int(create_time)
-                        publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
-                        article_url = article.get('link', '')
-                        video_dict = {
-                            'video_id': article.get('aid', ''),
-                            'video_title': article.get("title", "").replace(' ', '').replace('"', '').replace("'", ""),
-                            'publish_time_stamp': publish_time_stamp,
-                            'publish_time_str': publish_time_str,
-                            'user_name': user_dict["user_name"],
-                            'play_cnt': 0,
-                            'comment_cnt': 0,
-                            'like_cnt': 0,
-                            'share_cnt': 0,
-                            'user_id': user_dict['user_id'],
-                            'avatar_url': user_dict['avatar_url'],
-                            'cover_url': article.get('cover', ''),
-                            'article_url': article.get('link', ''),
-                            'video_url': cls.get_video_url(article_url, env),
-                            'session': f'gongzhonghao-author1-{int(time.time())}'
-                        }
-                        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 int(time.time()) - publish_time_stamp > 3600 * 24 * int(rule_dict.get('period', {}).get('max', 1000)):
-                            Common.logger(log_type, crawler).info(f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            Common.logging(log_type, crawler, env, f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            return
-
-                        if video_dict['article_url'] == 0 or video_dict['video_url'] == 0:
-                            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")
-                        # 标题相似度
-                        elif title_like(log_type, crawler, video_dict['video_title'], cls.platform, env) is True:
-                            Common.logger(log_type, crawler).info(f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                            Common.logging(log_type, crawler, env, f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                        else:
-                            # cls.download_publish(log_type=log_type,
-                            #                      crawler=crawler,
-                            #                      video_dict=video_dict,
-                            #                      rule_dict=rule_dict,
-                            #                      # user_dict=user_dict,
-                            #                      env=env)
-                            video_dict["out_user_id"] = video_dict["user_id"]
-                            video_dict["platform"] = crawler
-                            video_dict["strategy"] = log_type
-                            video_dict["out_video_id"] = video_dict["video_id"]
-                            video_dict["width"] = 0
-                            video_dict["height"] = 0
-                            video_dict["crawler_rule"] = json.dumps(rule_dict)
-                            # video_dict["user_id"] = user_dict["uid"]
-                            video_dict["user_id"] = Publish.uids(crawler, "定向爬虫策略", "", env)
-                            video_dict["publish_time"] = video_dict["publish_time_str"]
-
-                            mq.send_msg(video_dict)
-                    except Exception as e:
-                        Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
-                        Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
-                Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                time.sleep(60)
-
-    @classmethod
-    def repeat_video(cls, log_type, crawler, video_id, env):
-        # sql = f""" select * from crawler_video where platform="公众号" and out_video_id="{video_id}"; """
-        sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{video_id}"; """
-        repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
-        return len(repeat_video)
-
-    # 下载/上传
-    @classmethod
-    def download_publish(cls, log_type, crawler, 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
-        # 获取视频时长
-        ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
-        video_dict["video_width"] = ffmpeg_dict["width"]
-        video_dict["video_height"] = ffmpeg_dict["height"]
-        video_dict["duration"] = ffmpeg_dict["duration"]
-        Common.logger(log_type, crawler).info(f'video_width:{video_dict["video_width"]}')
-        Common.logging(log_type, crawler, env, f'video_width:{video_dict["video_width"]}')
-        Common.logger(log_type, crawler).info(f'video_height:{video_dict["video_height"]}')
-        Common.logging(log_type, crawler, env, f'video_height:{video_dict["video_height"]}')
-        Common.logger(log_type, crawler).info(f'duration:{video_dict["duration"]}')
-        Common.logging(log_type, crawler, env, f'duration:{video_dict["duration"]}')
-        if download_rule(log_type, crawler, video_dict, rule_dict) is False:
-            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"])
-        # 保存视频信息至 "./videos/{video_title}/info.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, "开始上传视频...")
-        strategy = "定向爬虫策略"
-        if env == 'prod':
-            oss_endpoint = "inner"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
-        else:
-            oss_endpoint = "out"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{str(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,
-                                                    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}")
-        Common.logging(log_type, crawler, env, f"insert_sql:{insert_sql}")
-        MysqlHelper.update_values(log_type, crawler, insert_sql, env)
-        Common.logger(log_type, crawler).info('视频信息写入数据库成功')
-        Common.logging(log_type, crawler, env, '视频信息写入数据库成功')
-
-        # 视频写入飞书
-        Feishu.insert_columns(log_type, crawler, "47e39d", "ROWS", 1, 2)
-        # 视频ID工作表,首行写入数据
-        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,
-                   int(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['article_url'],
-                   video_dict['video_url']]]
-        time.sleep(0.5)
-        Feishu.update_values(log_type, crawler, "47e39d", "F2:Z2", values)
-        Common.logger(log_type, crawler).info('视频下载/上传成功\n')
-        Common.logging(log_type, crawler, env, '视频下载/上传成功\n')
-
-    @classmethod
-    def get_all_videos(cls, log_type, crawler, rule_dict, env):
-        while True:
-            sheetid = "Bzv72P"
-            # sheetid = "SHRnwl"
-            user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
-            if user_sheet is None:
-                Common.logger(log_type, crawler).warning(f"user_sheet:{user_sheet}, 2秒后重试")
-                Common.logging(log_type, crawler, env, f"user_sheet:{user_sheet}, 2秒后重试")
-                time.sleep(2)
-                continue
-            len_sheet = len(user_sheet)
-            if len_sheet >= 141:
-                len_sheet = 141
-            for i in range(1, len_sheet):
-                user_dict = cls.get_users(log_type=log_type,
-                                          crawler=crawler,
-                                          user_sheet=user_sheet,
-                                          sheetid=sheetid,
-                                          i=i,
-                                          env=env)
-                Common.logger(log_type, crawler).info(f'获取 {user_dict["user_name"]} 公众号视频\n')
-                Common.logging(log_type, crawler, env, f'获取 {user_dict["user_name"]} 公众号视频\n')
-                try:
-                    cls.get_videoList(log_type=log_type,
-                                      crawler=crawler,
-                                      rule_dict=rule_dict,
-                                      user_dict=user_dict,
-                                      env=env)
-                    Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                    Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                    time.sleep(60)
-                except Exception as e:
-                    Common.logger(log_type, crawler).info(f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-                    Common.logging(log_type, crawler, env, f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-            break
-
-
-if __name__ == "__main__":
-    # GongzhonghaoAuthor1.get_token("author", "gongzhonghao", "prod")
-    # print(GongzhonghaoAuthor1.get_users("author", "gongzhonghao", "Bzv72P", "dev"))
-    # print(get_config_from_mysql("author", "gongzhonghao", "dev", "filter", action=""))
-    # print(title_like("author", "gongzhonghao", "公众号", "123", "dev"))
-    # print(GongzhonghaoAuthor1.get_user_info("author", "gongzhonghao", "幸福花朵", "dev"))
-    GongzhonghaoAuthor1.get_all_videos("author", "gongzhonghao", {}, "dev")
-    pass

+ 0 - 521
gongzhonghao/gongzhonghao_author/gongzhonghao2_author.py

@@ -1,521 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/3/28
-import datetime
-import json
-import os
-import shutil
-import sys
-import time
-from hashlib import md5
-import requests
-import urllib3
-from selenium.webdriver import DesiredCapabilities
-from selenium.webdriver.chrome.service import Service
-from selenium.webdriver.common.by import By
-from selenium import webdriver
-
-from common.mq import MQ
-sys.path.append(os.getcwd())
-# from common.getuser import getUser
-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, title_like, download_rule
-
-
-class GongzhonghaoAuthor2:
-    platform = "公众号"
-
-    # 获取 token
-    @classmethod
-    def get_token(cls, log_type, crawler, env):
-        select_sql = f""" select * from crawler_config where source="{crawler}" and title LIKE "%公众号_2%";"""
-        configs = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
-        if len(configs) == 0:
-            Feishu.bot(log_type, crawler, "公众号_2:未配置token")
-            time.sleep(60)
-            return None
-        token_dict = {
-            "token_id": configs[0]["id"],
-            "title": configs[0]["title"].strip(),
-            "token": dict(eval(configs[0]["config"]))["token"].strip(),
-            "cookie": dict(eval(configs[0]["config"]))["cookie"].strip(),
-            "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(configs[0]["update_time"]/1000))),
-            "operator": configs[0]["operator"].strip()
-        }
-        # for k, v in token_dict.items():
-        #     print(f"{k}:{v}")
-        return token_dict
-
-    @classmethod
-    def get_users(cls, log_type, crawler, user_sheet, sheetid, i, env):
-        user_name = user_sheet[i][0]
-        wechat_name = user_sheet[i][2]
-        if wechat_name is None or wechat_name.strip() == "" or wechat_name.replace(" ", "") == "":
-            wechat_name = user_name
-        out_uid = user_sheet[i][3]
-        avatar_url = user_sheet[i][4]
-        if out_uid is None or out_uid.strip() == "" or out_uid.replace(" ", "") == "":
-            user_info_dict = cls.get_user_info(log_type=log_type, crawler=crawler, wechat_name=wechat_name, env=env)
-            out_uid = user_info_dict["user_id"]
-            avatar_url = user_info_dict["avatar_url"]
-            Feishu.update_values(log_type, crawler, sheetid, f'D{i + 1}:E{i + 1}', [[out_uid, avatar_url]])
-
-        our_user_dict = {
-            'user_name': user_name,
-            'user_id': out_uid,
-            'wechat_name': wechat_name,
-            'avatar_url': avatar_url,
-        }
-        for k, v in our_user_dict.items():
-            Common.logger(log_type, crawler).info(f"{k}:{v}")
-        Common.logging(log_type, crawler, env, f'our_user_dict:{our_user_dict}')
-        return our_user_dict
-
-    # 获取用户 fakeid
-    @classmethod
-    def get_user_info(cls, log_type, crawler, wechat_name, env):
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=1011071554&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "search_biz",
-                "begin": "0",
-                "count": "5",
-                "query": str(wechat_name),
-                "token": token_dict['token'],
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if "list" not in r.json() or len(r.json()["list"]) == 0:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-
-            user_info_dict = {'user_name': r.json()["list"][0]["nickname"],
-                              'user_id': r.json()["list"][0]["fakeid"],
-                              'avatar_url': r.json()["list"][0]["round_head_img"]}
-            return user_info_dict
-
-    # 获取腾讯视频下载链接
-    @classmethod
-    def get_tencent_video_url(cls, video_id):
-        url = 'https://vv.video.qq.com/getinfo?vids=' + str(video_id) + '&platform=101001&charge=0&otype=json'
-        response = requests.get(url=url).text.replace('QZOutputJson=', '').replace('"};', '"}')
-        response = json.loads(response)
-        url = response['vl']['vi'][0]['ul']['ui'][0]['url']
-        fvkey = response['vl']['vi'][0]['fvkey']
-        video_url = url + str(video_id) + '.mp4?vkey=' + fvkey
-        return video_url
-
-    @classmethod
-    def get_video_url(cls, article_url, env):
-        # 打印请求配置
-        ca = DesiredCapabilities.CHROME
-        ca["goog:loggingPrefs"] = {"performance": "ALL"}
-
-        # 不打开浏览器运行
-        chrome_options = webdriver.ChromeOptions()
-        chrome_options.add_argument("headless")
-        chrome_options.add_argument(
-            f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36')
-        chrome_options.add_argument("--no-sandbox")
-
-        # driver初始化
-        if env == "prod":
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
-        else:
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service('/Users/wangkun/Downloads/chromedriver/chromedriver_v113/chromedriver'))
-
-        driver.implicitly_wait(10)
-        driver.get(article_url)
-        time.sleep(1)
-
-        if len(driver.find_elements(By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]')) != 0:
-            video_url = driver.find_element(
-                By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]').get_attribute('src')
-        elif len(driver.find_elements(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]')) != 0:
-            iframe = driver.find_element(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]').get_attribute(
-                'src')
-            video_id = iframe.split('vid=')[-1].split('&')[0]
-            video_url = cls.get_tencent_video_url(video_id)
-        else:
-            video_url = 0
-        driver.quit()
-        return video_url
-
-    # 获取文章列表
-    @classmethod
-    def get_videoList(cls, log_type, crawler, rule_dict, user_dict, env):
-        mq = MQ(topic_name="topic_crawler_etl_" + env)
-        begin = 0
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=" + str(token_dict['token']) + "&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "list_ex",
-                "begin": str(begin),
-                "count": "5",
-                "fakeid": user_dict['user_id'],
-                "type": "9",
-                "query": "",
-                "token": str(token_dict['token']),
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "invalid args" and r.json()["base_resp"]["ret"] == 200002:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"公众号:{user_dict['user_name']}\n抓取异常, 请检查该公众号\n")
-                return
-            if 'app_msg_list' not in r.json():
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if len(r.json()['app_msg_list']) == 0:
-                Common.logger(log_type, crawler).info('没有更多视频了\n')
-                Common.logging(log_type, crawler, env, '没有更多视频了\n')
-                return
-            else:
-                begin += 5
-                app_msg_list = r.json()['app_msg_list']
-                for article in app_msg_list:
-                    try:
-                        create_time = article.get('create_time', 0)
-                        publish_time_stamp = int(create_time)
-                        publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
-                        article_url = article.get('link', '')
-                        video_dict = {
-                            'video_id': article.get('aid', ''),
-                            'video_title': article.get("title", "").replace(' ', '').replace('"', '').replace("'", ""),
-                            'publish_time_stamp': publish_time_stamp,
-                            'publish_time_str': publish_time_str,
-                            'user_name': user_dict["user_name"],
-                            'play_cnt': 0,
-                            'comment_cnt': 0,
-                            'like_cnt': 0,
-                            'share_cnt': 0,
-                            'user_id': user_dict['user_id'],
-                            'avatar_url': user_dict['avatar_url'],
-                            'cover_url': article.get('cover', ''),
-                            'article_url': article.get('link', ''),
-                            'video_url': cls.get_video_url(article_url, env),
-                            'session': f'gongzhonghao-author1-{int(time.time())}'
-                        }
-                        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 int(time.time()) - publish_time_stamp > 3600 * 24 * int(rule_dict.get('period', {}).get('max', 1000)):
-                            Common.logger(log_type, crawler).info(f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            Common.logging(log_type, crawler, env, f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            return
-
-                        if video_dict['article_url'] == 0 or video_dict['video_url'] == 0:
-                            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")
-                        # 标题相似度
-                        elif title_like(log_type, crawler, video_dict['video_title'], cls.platform, env) is True:
-                            Common.logger(log_type, crawler).info(f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                            Common.logging(log_type, crawler, env, f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                        else:
-                            # cls.download_publish(log_type=log_type,
-                            #                      crawler=crawler,
-                            #                      video_dict=video_dict,
-                            #                      rule_dict=rule_dict,
-                            #                      # user_dict=user_dict,
-                            #                      env=env)
-                            video_dict["out_user_id"] = video_dict["user_id"]
-                            video_dict["platform"] = crawler
-                            video_dict["strategy"] = log_type
-                            video_dict["out_video_id"] = video_dict["video_id"]
-                            video_dict["width"] = 0
-                            video_dict["height"] = 0
-                            video_dict["crawler_rule"] = json.dumps(rule_dict)
-                            # video_dict["user_id"] = user_dict["uid"]
-                            video_dict["user_id"] = Publish.uids(crawler, "定向爬虫策略", "", env)
-                            video_dict["publish_time"] = video_dict["publish_time_str"]
-
-                            mq.send_msg(video_dict)
-                    except Exception as e:
-                        Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
-                        Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
-
-                Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                time.sleep(60)
-
-    @classmethod
-    def repeat_video(cls, log_type, crawler, video_id, env):
-        # sql = f""" select * from crawler_video where platform="公众号" and out_video_id="{video_id}"; """
-        sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{video_id}"; """
-        repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
-        return len(repeat_video)
-
-    # 下载/上传
-    @classmethod
-    def download_publish(cls, log_type, crawler, 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
-        # 获取视频时长
-        ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
-        video_dict["video_width"] = ffmpeg_dict["width"]
-        video_dict["video_height"] = ffmpeg_dict["height"]
-        video_dict["duration"] = ffmpeg_dict["duration"]
-        Common.logger(log_type, crawler).info(f'video_width:{video_dict["video_width"]}')
-        Common.logging(log_type, crawler, env, f'video_width:{video_dict["video_width"]}')
-        Common.logger(log_type, crawler).info(f'video_height:{video_dict["video_height"]}')
-        Common.logging(log_type, crawler, env, f'video_height:{video_dict["video_height"]}')
-        Common.logger(log_type, crawler).info(f'duration:{video_dict["duration"]}')
-        Common.logging(log_type, crawler, env, f'duration:{video_dict["duration"]}')
-        if download_rule(log_type, crawler, video_dict, rule_dict) is False:
-            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"])
-        # 保存视频信息至 "./videos/{video_title}/info.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, "开始上传视频...")
-        strategy = "定向爬虫策略"
-        if env == 'prod':
-            oss_endpoint = "inner"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
-        else:
-            oss_endpoint = "out"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{str(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,
-                                                    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}")
-        Common.logging(log_type, crawler, env, f"insert_sql:{insert_sql}")
-        MysqlHelper.update_values(log_type, crawler, insert_sql, env)
-        Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
-        Common.logging(log_type, crawler, env, '视频信息插入数据库成功!')
-
-        # 视频写入飞书
-        Feishu.insert_columns(log_type, crawler, "47e39d", "ROWS", 1, 2)
-        # 视频ID工作表,首行写入数据
-        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,
-                   int(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['article_url'],
-                   video_dict['video_url']]]
-        time.sleep(0.5)
-        Feishu.update_values(log_type, crawler, "47e39d", "F2:Z2", values)
-        Common.logger(log_type, crawler).info('视频下载/上传成功\n')
-        Common.logging(log_type, crawler, env, '视频下载/上传成功\n')
-
-    @classmethod
-    def get_all_videos(cls, log_type, crawler, rule_dict, env):
-        while True:
-            sheetid = "Bzv72P"
-            user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
-            if user_sheet is None:
-                Common.logger(log_type, crawler).warning(f"user_sheet:{user_sheet}, 2秒后重试")
-                Common.logging(log_type, crawler, env, f"user_sheet:{user_sheet}, 2秒后重试")
-                time.sleep(2)
-                continue
-            len_sheet = len(user_sheet)
-            if len_sheet <= 141:
-                Common.logger(log_type, crawler).info("抓取用户数<=100,无需启动第二套抓取脚本\n")
-                Common.logging(log_type, crawler, env, "抓取用户数<=100,无需启动第二套抓取脚本\n")
-                return
-            if len_sheet >= 261:
-                len_sheet = 261
-            for i in range(141, len_sheet):
-                user_dict = cls.get_users(log_type=log_type,
-                                          crawler=crawler,
-                                          user_sheet=user_sheet,
-                                          sheetid=sheetid,
-                                          i=i,
-                                          env=env)
-                Common.logger(log_type, crawler).info(f'获取 {user_dict["user_name"]} 公众号视频\n')
-                Common.logging(log_type, crawler, env, f'获取 {user_dict["user_name"]} 公众号视频\n')
-                try:
-                    cls.get_videoList(log_type=log_type,
-                                      crawler=crawler,
-                                      rule_dict=rule_dict,
-                                      user_dict=user_dict,
-                                      env=env)
-                    Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                    Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                    time.sleep(60)
-                except Exception as e:
-                    Common.logger(log_type, crawler).info(f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-                    Common.logging(log_type, crawler, env, f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-            break
-
-
-if __name__ == "__main__":
-    GongzhonghaoAuthor2.get_token("author", "gongzhonghao", "dev")
-    pass

+ 0 - 522
gongzhonghao/gongzhonghao_author/gongzhonghao3_author.py

@@ -1,522 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/3/28
-import datetime
-import json
-import os
-import shutil
-import sys
-import time
-from hashlib import md5
-import requests
-import urllib3
-from selenium.webdriver import DesiredCapabilities
-from selenium.webdriver.chrome.service import Service
-from selenium.webdriver.common.by import By
-from selenium import webdriver
-
-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.scheduling_db import MysqlHelper
-from common.public import get_config_from_mysql, title_like, download_rule
-
-
-class GongzhonghaoAuthor3:
-    platform = "公众号"
-
-    # 获取 token
-    @classmethod
-    def get_token(cls, log_type, crawler, env):
-        select_sql = f""" select * from crawler_config where source="{crawler}" and title LIKE "%公众号_3%";"""
-        configs = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
-        if len(configs) == 0:
-            Feishu.bot(log_type, crawler, "公众号_3:未配置token\n请登录后配置\nhttps://admin.piaoquantv.com/cms/spider-source-config")
-            time.sleep(60)
-            return None
-        token_dict = {
-            "token_id": configs[0]["id"],
-            "title": configs[0]["title"].strip(),
-            "token": dict(eval(configs[0]["config"]))["token"].strip(),
-            "cookie": dict(eval(configs[0]["config"]))["cookie"].strip(),
-            "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(configs[0]["update_time"]/1000))),
-            "operator": configs[0]["operator"].strip()
-        }
-        # for k, v in token_dict.items():
-        #     print(f"{k}:{v}")
-        return token_dict
-
-    @classmethod
-    def get_users(cls, log_type, crawler, user_sheet, sheetid, i, env):
-        user_name = user_sheet[i][0]
-        wechat_name = user_sheet[i][2]
-        if wechat_name is None or wechat_name.strip() == "" or wechat_name.replace(" ", "") == "":
-            wechat_name = user_name
-        out_uid = user_sheet[i][3]
-        avatar_url = user_sheet[i][4]
-        if out_uid is None or out_uid.strip() == "" or out_uid.replace(" ", "") == "":
-            user_info_dict = cls.get_user_info(log_type=log_type, crawler=crawler, wechat_name=wechat_name, env=env)
-            out_uid = user_info_dict["user_id"]
-            avatar_url = user_info_dict["avatar_url"]
-            Feishu.update_values(log_type, crawler, sheetid, f'D{i + 1}:E{i + 1}', [[out_uid, avatar_url]])
-
-        our_user_dict = {
-            'user_name': user_name,
-            'user_id': out_uid,
-            'wechat_name': wechat_name,
-            'avatar_url': avatar_url,
-        }
-        for k, v in our_user_dict.items():
-            Common.logger(log_type, crawler).info(f"{k}:{v}")
-        Common.logging(log_type, crawler, env, f"our_user_dict:{our_user_dict}")
-        return our_user_dict
-
-    # 获取用户 fakeid
-    @classmethod
-    def get_user_info(cls, log_type, crawler, wechat_name, env):
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=1011071554&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "search_biz",
-                "begin": "0",
-                "count": "5",
-                "query": str(wechat_name),
-                "token": token_dict['token'],
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if "list" not in r.json() or len(r.json()["list"]) == 0:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-
-            user_info_dict = {'user_name': r.json()["list"][0]["nickname"],
-                              'user_id': r.json()["list"][0]["fakeid"],
-                              'avatar_url': r.json()["list"][0]["round_head_img"]}
-            return user_info_dict
-
-    # 获取腾讯视频下载链接
-    @classmethod
-    def get_tencent_video_url(cls, video_id):
-        url = 'https://vv.video.qq.com/getinfo?vids=' + str(video_id) + '&platform=101001&charge=0&otype=json'
-        response = requests.get(url=url).text.replace('QZOutputJson=', '').replace('"};', '"}')
-        response = json.loads(response)
-        url = response['vl']['vi'][0]['ul']['ui'][0]['url']
-        fvkey = response['vl']['vi'][0]['fvkey']
-        video_url = url + str(video_id) + '.mp4?vkey=' + fvkey
-        return video_url
-
-    @classmethod
-    def get_video_url(cls, article_url, env):
-        # 打印请求配置
-        ca = DesiredCapabilities.CHROME
-        ca["goog:loggingPrefs"] = {"performance": "ALL"}
-
-        # 不打开浏览器运行
-        chrome_options = webdriver.ChromeOptions()
-        chrome_options.add_argument("headless")
-        chrome_options.add_argument(
-            f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36')
-        chrome_options.add_argument("--no-sandbox")
-
-        # driver初始化
-        if env == "prod":
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
-        else:
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service(
-                '/Users/wangkun/Downloads/chromedriver/chromedriver_v113/chromedriver'))
-
-        driver.implicitly_wait(10)
-        driver.get(article_url)
-        time.sleep(1)
-
-        if len(driver.find_elements(By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]')) != 0:
-            video_url = driver.find_element(
-                By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]').get_attribute('src')
-        elif len(driver.find_elements(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]')) != 0:
-            iframe = driver.find_element(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]').get_attribute(
-                'src')
-            video_id = iframe.split('vid=')[-1].split('&')[0]
-            video_url = cls.get_tencent_video_url(video_id)
-        else:
-            video_url = 0
-        driver.quit()
-        return video_url
-
-    # 获取文章列表
-    @classmethod
-    def get_videoList(cls, log_type, crawler, rule_dict, user_dict, env):
-        mq = MQ(topic_name="topic_crawler_etl_" + env)
-        begin = 0
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=" + str(token_dict['token']) + "&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "list_ex",
-                "begin": str(begin),
-                "count": "5",
-                "fakeid": user_dict['user_id'],
-                "type": "9",
-                "query": "",
-                "token": str(token_dict['token']),
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "invalid args" and r.json()["base_resp"]["ret"] == 200002:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"公众号:{user_dict['user_name']}\n抓取异常, 请检查该公众号\n")
-                return
-            if 'app_msg_list' not in r.json():
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if len(r.json()['app_msg_list']) == 0:
-                Common.logger(log_type, crawler).info('没有更多视频了\n')
-                Common.logging(log_type, crawler, env, '没有更多视频了\n')
-                return
-            else:
-                begin += 5
-                app_msg_list = r.json()['app_msg_list']
-                for article in app_msg_list:
-                    try:
-                        create_time = article.get('create_time', 0)
-                        publish_time_stamp = int(create_time)
-                        publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
-                        article_url = article.get('link', '')
-                        video_dict = {
-                            'video_id': article.get('aid', ''),
-                            'video_title': article.get("title", "").replace(' ', '').replace('"', '').replace("'", ""),
-                            'publish_time_stamp': publish_time_stamp,
-                            'publish_time_str': publish_time_str,
-                            'user_name': user_dict["user_name"],
-                            'play_cnt': 0,
-                            'comment_cnt': 0,
-                            'like_cnt': 0,
-                            'share_cnt': 0,
-                            'user_id': user_dict['user_id'],
-                            'avatar_url': user_dict['avatar_url'],
-                            'cover_url': article.get('cover', ''),
-                            'article_url': article.get('link', ''),
-                            'video_url': cls.get_video_url(article_url, env),
-                            'session': f'gongzhonghao-author1-{int(time.time())}'
-                        }
-                        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 int(time.time()) - publish_time_stamp > 3600 * 24 * int(
-                                rule_dict.get('period', {}).get('max', 1000)):
-                            Common.logger(log_type, crawler).info(f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            Common.logging(log_type, crawler, env, f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            return
-
-                        if video_dict['article_url'] == 0 or video_dict['video_url'] == 0:
-                            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")
-                        # 标题相似度
-                        elif title_like(log_type, crawler, video_dict['video_title'], cls.platform, env) is True:
-                            Common.logger(log_type, crawler).info(f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                            Common.logging(log_type, crawler, env, f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                        else:
-                            # cls.download_publish(log_type=log_type,
-                            #                      crawler=crawler,
-                            #                      video_dict=video_dict,
-                            #                      rule_dict=rule_dict,
-                            #                      # user_dict=user_dict,
-                            #                      env=env)
-                            video_dict["out_user_id"] = video_dict["user_id"]
-                            video_dict["platform"] = crawler
-                            video_dict["strategy"] = log_type
-                            video_dict["out_video_id"] = video_dict["video_id"]
-                            video_dict["width"] = 0
-                            video_dict["height"] = 0
-                            video_dict["crawler_rule"] = json.dumps(rule_dict)
-                            # video_dict["user_id"] = user_dict["uid"]
-                            video_dict["user_id"] = Publish.uids(crawler, "定向爬虫策略", "", env)
-                            video_dict["publish_time"] = video_dict["publish_time_str"]
-
-                            mq.send_msg(video_dict)
-                    except Exception as e:
-                        Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
-                        Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
-
-                Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                time.sleep(60)
-
-    @classmethod
-    def repeat_video(cls, log_type, crawler, video_id, env):
-        # sql = f""" select * from crawler_video where platform="公众号" and out_video_id="{video_id}"; """
-        sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{video_id}"; """
-        repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
-        return len(repeat_video)
-
-    # 下载/上传
-    @classmethod
-    def download_publish(cls, log_type, crawler, 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
-        # 获取视频时长
-        ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
-        video_dict["video_width"] = ffmpeg_dict["width"]
-        video_dict["video_height"] = ffmpeg_dict["height"]
-        video_dict["duration"] = ffmpeg_dict["duration"]
-        Common.logger(log_type, crawler).info(f'video_width:{video_dict["video_width"]}')
-        Common.logging(log_type, crawler, env, f'video_width:{video_dict["video_width"]}')
-        Common.logger(log_type, crawler).info(f'video_height:{video_dict["video_height"]}')
-        Common.logging(log_type, crawler, env, f'video_height:{video_dict["video_height"]}')
-        Common.logger(log_type, crawler).info(f'duration:{video_dict["duration"]}')
-        Common.logging(log_type, crawler, env, f'duration:{video_dict["duration"]}')
-        if download_rule(log_type, crawler, video_dict, rule_dict) is False:
-            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"])
-        # 保存视频信息至 "./videos/{video_title}/info.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, "开始上传视频...")
-        strategy = "定向爬虫策略"
-        if env == 'prod':
-            oss_endpoint = "inner"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
-        else:
-            oss_endpoint = "out"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{str(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,
-                                                    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}")
-        Common.logging(log_type, crawler, env, f"insert_sql:{insert_sql}")
-        MysqlHelper.update_values(log_type, crawler, insert_sql, env)
-        Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
-        Common.logging(log_type, crawler, env, '视频信息插入数据库成功!')
-
-        # 视频写入飞书
-        Feishu.insert_columns(log_type, crawler, "47e39d", "ROWS", 1, 2)
-        # 视频ID工作表,首行写入数据
-        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,
-                   int(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['article_url'],
-                   video_dict['video_url']]]
-        time.sleep(0.5)
-        Feishu.update_values(log_type, crawler, "47e39d", "F2:Z2", values)
-        Common.logger(log_type, crawler).info('视频下载/上传成功\n')
-        Common.logging(log_type, crawler, env, '视频下载/上传成功\n')
-
-    @classmethod
-    def get_all_videos(cls, log_type, crawler, rule_dict, env):
-        while True:
-            sheetid = "Bzv72P"
-            user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
-            if user_sheet is None:
-                Common.logger(log_type, crawler).warning(f"user_sheet:{user_sheet}, 2秒后重试")
-                Common.logging(log_type, crawler, env, f"user_sheet:{user_sheet}, 2秒后重试")
-                time.sleep(2)
-                continue
-            len_sheet = len(user_sheet)
-            if len_sheet <= 261:
-                Common.logger(log_type, crawler).info("抓取用户数<=200,无需启动第三套抓取脚本\n")
-                Common.logging(log_type, crawler, env, "抓取用户数<=200,无需启动第三套抓取脚本\n")
-                return
-            if len_sheet >= 361:
-                len_sheet = 361
-            for i in range(261, len_sheet):
-                user_dict = cls.get_users(log_type=log_type,
-                                          crawler=crawler,
-                                          user_sheet=user_sheet,
-                                          sheetid=sheetid,
-                                          i=i,
-                                          env=env)
-                Common.logger(log_type, crawler).info(f'获取 {user_dict["user_name"]} 公众号视频\n')
-                Common.logging(log_type, crawler, env, f'获取 {user_dict["user_name"]} 公众号视频\n')
-                try:
-                    cls.get_videoList(log_type=log_type,
-                                      crawler=crawler,
-                                      rule_dict=rule_dict,
-                                      user_dict=user_dict,
-                                      env=env)
-                    Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                    Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                    time.sleep(60)
-                except Exception as e:
-                    Common.logger(log_type, crawler).info(f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-                    Common.logging(log_type, crawler, env, f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-            break
-
-
-if __name__ == "__main__":
-    GongzhonghaoAuthor3.get_token("author", "gongzhonghao", "dev")
-    pass

+ 0 - 522
gongzhonghao/gongzhonghao_author/gongzhonghao4_author.py

@@ -1,522 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/3/28
-import datetime
-# import difflib
-import json
-import os
-import shutil
-import sys
-import time
-from hashlib import md5
-import requests
-import urllib3
-from selenium.webdriver import DesiredCapabilities
-from selenium.webdriver.chrome.service import Service
-from selenium.webdriver.common.by import By
-from selenium import webdriver
-
-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.scheduling_db import MysqlHelper
-from common.public import get_config_from_mysql, title_like, download_rule
-
-
-class GongzhonghaoAuthor4:
-    platform = "公众号"
-
-    # 获取 token
-    @classmethod
-    def get_token(cls, log_type, crawler, env):
-        select_sql = f""" select * from crawler_config where source="{crawler}" and title LIKE "%公众号_4%";"""
-        configs = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
-        if len(configs) == 0:
-            Feishu.bot(log_type, crawler, "公众号_4:未配置token")
-            time.sleep(60)
-            return None
-        token_dict = {
-            "token_id": configs[0]["id"],
-            "title": configs[0]["title"],
-            "token": dict(eval(configs[0]["config"]))["token"],
-            "cookie": dict(eval(configs[0]["config"]))["cookie"],
-            "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(configs[0]["update_time"]/1000))),
-            "operator": configs[0]["operator"]
-        }
-        # for k, v in token_dict.items():
-        #     print(f"{k}:{v}")
-        return token_dict
-
-    @classmethod
-    def get_users(cls, log_type, crawler, user_sheet, sheetid, i, env):
-        user_name = user_sheet[i][0]
-        wechat_name = user_sheet[i][2]
-        if wechat_name is None or wechat_name.strip() == "" or wechat_name.replace(" ", "") == "":
-            wechat_name = user_name
-        out_uid = user_sheet[i][3]
-        avatar_url = user_sheet[i][4]
-        if out_uid is None or out_uid.strip() == "" or out_uid.replace(" ", "") == "":
-            user_info_dict = cls.get_user_info(log_type=log_type, crawler=crawler, wechat_name=wechat_name, env=env)
-            out_uid = user_info_dict["user_id"]
-            avatar_url = user_info_dict["avatar_url"]
-            Feishu.update_values(log_type, crawler, sheetid, f'D{i + 1}:E{i + 1}', [[out_uid, avatar_url]])
-
-        our_user_dict = {
-            'user_name': user_name,
-            'user_id': out_uid,
-            'wechat_name': wechat_name,
-            'avatar_url': avatar_url,
-        }
-        for k, v in our_user_dict.items():
-            Common.logger(log_type, crawler).info(f"{k}:{v}")
-        Common.logging(log_type, crawler, env, f'our_user_dict:{our_user_dict}')
-        return our_user_dict
-
-    # 获取用户 fakeid
-    @classmethod
-    def get_user_info(cls, log_type, crawler, wechat_name, env):
-        Common.logger(log_type, crawler).info(f"获取站外用户信息:{wechat_name}")
-        Common.logging(log_type, crawler, env, f"获取站外用户信息:{wechat_name}")
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=1011071554&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "search_biz",
-                "begin": "0",
-                "count": "5",
-                "query": str(wechat_name),
-                "token": token_dict['token'],
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if "list" not in r.json() or len(r.json()["list"]) == 0:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            user_info_dict = {'user_name': r.json()["list"][0]["nickname"],
-                              'user_id': r.json()["list"][0]["fakeid"],
-                              'avatar_url': r.json()["list"][0]["round_head_img"]}
-            return user_info_dict
-
-    # 获取腾讯视频下载链接
-    @classmethod
-    def get_tencent_video_url(cls, video_id):
-        url = 'https://vv.video.qq.com/getinfo?vids=' + str(video_id) + '&platform=101001&charge=0&otype=json'
-        response = requests.get(url=url).text.replace('QZOutputJson=', '').replace('"};', '"}')
-        response = json.loads(response)
-        url = response['vl']['vi'][0]['ul']['ui'][0]['url']
-        fvkey = response['vl']['vi'][0]['fvkey']
-        video_url = url + str(video_id) + '.mp4?vkey=' + fvkey
-        return video_url
-
-    @classmethod
-    def get_video_url(cls, article_url, env):
-        # 打印请求配置
-        ca = DesiredCapabilities.CHROME
-        ca["goog:loggingPrefs"] = {"performance": "ALL"}
-
-        # 不打开浏览器运行
-        chrome_options = webdriver.ChromeOptions()
-        chrome_options.add_argument("headless")
-        chrome_options.add_argument(
-            f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36')
-        chrome_options.add_argument("--no-sandbox")
-
-        # driver初始化
-        if env == "prod":
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
-        else:
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service(
-                '/Users/wangkun/Downloads/chromedriver/chromedriver_v113/chromedriver'))
-
-        driver.implicitly_wait(10)
-        driver.get(article_url)
-        time.sleep(1)
-
-        if len(driver.find_elements(By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]')) != 0:
-            video_url = driver.find_element(
-                By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]').get_attribute('src')
-        elif len(driver.find_elements(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]')) != 0:
-            iframe = driver.find_element(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]').get_attribute(
-                'src')
-            video_id = iframe.split('vid=')[-1].split('&')[0]
-            video_url = cls.get_tencent_video_url(video_id)
-        else:
-            video_url = 0
-        driver.quit()
-        return video_url
-
-    # 获取文章列表
-    @classmethod
-    def get_videoList(cls, log_type, crawler, rule_dict, user_dict, env):
-        mq = MQ(topic_name="topic_crawler_etl_" + env)
-        begin = 0
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=" + str(token_dict['token']) + "&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "list_ex",
-                "begin": str(begin),
-                "count": "5",
-                "fakeid": user_dict['user_id'],
-                "type": "9",
-                "query": "",
-                "token": str(token_dict['token']),
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "invalid args" and r.json()["base_resp"]["ret"] == 200002:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"公众号:{user_dict['user_name']}\n抓取异常, 请检查该公众号\n")
-                return
-            if 'app_msg_list' not in r.json():
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if len(r.json()['app_msg_list']) == 0:
-                Common.logger(log_type, crawler).info('没有更多视频了\n')
-                Common.logging(log_type, crawler, env, '没有更多视频了\n')
-                return
-            else:
-                begin += 5
-                app_msg_list = r.json()['app_msg_list']
-                for article in app_msg_list:
-                    try:
-                        create_time = article.get('create_time', 0)
-                        publish_time_stamp = int(create_time)
-                        publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
-                        article_url = article.get('link', '')
-                        video_dict = {
-                            'video_id': article.get('aid', ''),
-                            'video_title': article.get("title", "").replace(' ', '').replace('"', '').replace("'", ""),
-                            'publish_time_stamp': publish_time_stamp,
-                            'publish_time_str': publish_time_str,
-                            'user_name': user_dict["user_name"],
-                            'play_cnt': 0,
-                            'comment_cnt': 0,
-                            'like_cnt': 0,
-                            'share_cnt': 0,
-                            'user_id': user_dict['user_id'],
-                            'avatar_url': user_dict['avatar_url'],
-                            'cover_url': article.get('cover', ''),
-                            'article_url': article.get('link', ''),
-                            'video_url': cls.get_video_url(article_url, env),
-                            'session': f'gongzhonghao-author1-{int(time.time())}'
-                        }
-                        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 int(time.time()) - publish_time_stamp > 3600 * 24 * int(rule_dict.get('period', {}).get('max', 1000)):
-                            Common.logger(log_type, crawler).info(f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            Common.logging(log_type, crawler, env, "发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            return
-
-                        if video_dict['article_url'] == 0 or video_dict['video_url'] == 0:
-                            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")
-                        # 标题相似度
-                        elif title_like(log_type, crawler, video_dict['video_title'], cls.platform, env) is True:
-                            Common.logger(log_type, crawler).info(f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                            Common.logging(log_type, crawler, env, f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                        else:
-                            # cls.download_publish(log_type=log_type,
-                            #                      crawler=crawler,
-                            #                      video_dict=video_dict,
-                            #                      rule_dict=rule_dict,
-                            #                      # user_dict=user_dict,
-                            #                      env=env)
-                            video_dict["out_user_id"] = video_dict["user_id"]
-                            video_dict["platform"] = crawler
-                            video_dict["strategy"] = log_type
-                            video_dict["out_video_id"] = video_dict["video_id"]
-                            video_dict["width"] = 0
-                            video_dict["height"] = 0
-                            video_dict["crawler_rule"] = json.dumps(rule_dict)
-                            # video_dict["user_id"] = user_dict["uid"]
-                            video_dict["user_id"] = Publish.uids(crawler, "定向爬虫策略", "", env)
-                            video_dict["publish_time"] = video_dict["publish_time_str"]
-
-                            mq.send_msg(video_dict)
-                    except Exception as e:
-                        Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
-                        Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
-                Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                time.sleep(60)
-
-
-    @classmethod
-    def repeat_video(cls, log_type, crawler, video_id, env):
-        # sql = f""" select * from crawler_video where platform="公众号" and out_video_id="{video_id}"; """
-        sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{video_id}"; """
-        repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
-        return len(repeat_video)
-
-    # 下载/上传
-    @classmethod
-    def download_publish(cls, log_type, crawler, 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
-        # 获取视频时长
-        ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
-        video_dict["video_width"] = ffmpeg_dict["width"]
-        video_dict["video_height"] = ffmpeg_dict["height"]
-        video_dict["duration"] = ffmpeg_dict["duration"]
-        Common.logger(log_type, crawler).info(f'video_width:{video_dict["video_width"]}')
-        Common.logging(log_type, crawler, env, f'video_width:{video_dict["video_width"]}')
-        Common.logger(log_type, crawler).info(f'video_height:{video_dict["video_height"]}')
-        Common.logging(log_type, crawler, env, f'video_height:{video_dict["video_height"]}')
-        Common.logger(log_type, crawler).info(f'duration:{video_dict["duration"]}')
-        Common.logging(log_type, crawler, env, f'duration:{video_dict["duration"]}')
-        if download_rule(log_type, crawler, video_dict, rule_dict) is False:
-            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"])
-        # 保存视频信息至 "./videos/{video_title}/info.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, "开始上传视频...")
-        strategy = "定向爬虫策略"
-        if env == 'prod':
-            oss_endpoint = "inner"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
-        else:
-            oss_endpoint = "out"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{str(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,
-                                                    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}")
-        Common.logging(log_type, crawler, env, f"insert_sql:{insert_sql}")
-        MysqlHelper.update_values(log_type, crawler, insert_sql, env)
-        Common.logger(log_type, crawler).info('视频信息写入数据库成功')
-        Common.logging(log_type, crawler, env, '视频信息写入数据库成功')
-
-        # 视频写入飞书
-        Feishu.insert_columns(log_type, crawler, "47e39d", "ROWS", 1, 2)
-        # 视频ID工作表,首行写入数据
-        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,
-                   int(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['article_url'],
-                   video_dict['video_url']]]
-        time.sleep(0.5)
-        Feishu.update_values(log_type, crawler, "47e39d", "F2:Z2", values)
-        Common.logger(log_type, crawler).info('视频下载/上传成功\n')
-        Common.logging(log_type, crawler, env, '视频下载/上传成功\n')
-
-    @classmethod
-    def get_all_videos(cls, log_type, crawler, rule_dict, env):
-        while True:
-            sheetid = "Bzv72P"
-            user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
-            if user_sheet is None:
-                Common.logger(log_type, crawler).warning(f"user_sheet:{user_sheet}, 2秒后重试")
-                Common.logging(log_type, crawler, env, f"user_sheet:{user_sheet}, 2秒后重试")
-                time.sleep(2)
-                continue
-            len_sheet = len(user_sheet)
-            if len_sheet <= 361:
-                Common.logger(log_type, crawler).info("抓取用户数<=300,无需启动第四套抓取脚本\n")
-                Common.logging(log_type, crawler, env, "抓取用户数<=300,无需启动第四套抓取脚本\n")
-                return
-            if len_sheet >= 461:
-                len_sheet = 461
-            for i in range(361, len_sheet):
-                user_dict = cls.get_users(log_type=log_type,
-                                          crawler=crawler,
-                                          user_sheet=user_sheet,
-                                          sheetid=sheetid,
-                                          i=i,
-                                          env=env)
-                Common.logger(log_type, crawler).info(f'获取:{user_dict["user_name"]} 公众号视频\n')
-                Common.logging(log_type, crawler, env, f'获取:{user_dict["user_name"]} 公众号视频\n')
-                try:
-                    cls.get_videoList(log_type=log_type,
-                                      crawler=crawler,
-                                      rule_dict=rule_dict,
-                                      user_dict=user_dict,
-                                      env=env)
-                    Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                    Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                    time.sleep(60)
-                except Exception as e:
-                    Common.logger(log_type, crawler).info(f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-                    Common.logging(log_type, crawler, env, f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-            break
-
-if __name__ == "__main__":
-    GongzhonghaoAuthor4.get_token("author", "gongzhonghao", "dev")
-    pass

+ 0 - 525
gongzhonghao/gongzhonghao_author/gongzhonghao5_author.py

@@ -1,525 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/3/28
-import datetime
-# import difflib
-import json
-import os
-import shutil
-import sys
-import time
-from hashlib import md5
-import requests
-import urllib3
-from selenium.webdriver import DesiredCapabilities
-from selenium.webdriver.chrome.service import Service
-from selenium.webdriver.common.by import By
-from selenium import webdriver
-
-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.scheduling_db import MysqlHelper
-from common.public import get_config_from_mysql, title_like, download_rule
-
-
-class GongzhonghaoAuthor5:
-    platform = "公众号"
-
-    # 获取 token
-    @classmethod
-    def get_token(cls, log_type, crawler, env):
-        select_sql = f""" select * from crawler_config where source="{crawler}" and title LIKE "%公众号_5%";"""
-        configs = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
-        if len(configs) == 0:
-            Feishu.bot(log_type, crawler, "公众号_5:未配置token")
-            time.sleep(60)
-            return None
-        token_dict = {
-            "token_id": configs[0]["id"],
-            "title": configs[0]["title"],
-            "token": dict(eval(configs[0]["config"]))["token"],
-            "cookie": dict(eval(configs[0]["config"]))["cookie"],
-            "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(configs[0]["update_time"]/1000))),
-            "operator": configs[0]["operator"]
-        }
-        for k, v in token_dict.items():
-            print(f"{k}:{v}")
-        return token_dict
-
-    @classmethod
-    def get_users(cls, log_type, crawler, user_sheet, sheetid, i, env):
-        user_name = user_sheet[i][0]
-        wechat_name = user_sheet[i][2]
-        if wechat_name is None or wechat_name.strip() == "" or wechat_name.replace(" ", "") == "":
-            wechat_name = user_name
-        out_uid = user_sheet[i][3]
-        avatar_url = user_sheet[i][4]
-        if out_uid is None or out_uid.strip() == "" or out_uid.replace(" ", "") == "":
-            user_info_dict = cls.get_user_info(log_type=log_type, crawler=crawler, wechat_name=wechat_name, env=env)
-            out_uid = user_info_dict["user_id"]
-            avatar_url = user_info_dict["avatar_url"]
-            Feishu.update_values(log_type, crawler, sheetid, f'D{i + 1}:E{i + 1}', [[out_uid, avatar_url]])
-
-        our_user_dict = {
-            'user_name': user_name,
-            'user_id': out_uid,
-            'wechat_name': wechat_name,
-            'avatar_url': avatar_url,
-        }
-        for k, v in our_user_dict.items():
-            Common.logger(log_type, crawler).info(f"{k}:{v}")
-        Common.logging(log_type, crawler, env, f"our_user_dict:{our_user_dict}")
-        return our_user_dict
-
-    # 获取用户 fakeid
-    @classmethod
-    def get_user_info(cls, log_type, crawler, wechat_name, env):
-        Common.logger(log_type, crawler).info(f"获取站外用户信息:{wechat_name}")
-        Common.logging(log_type, crawler, env, f"获取站外用户信息:{wechat_name}")
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=1011071554&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "search_biz",
-                "begin": "0",
-                "count": "5",
-                "query": str(wechat_name),
-                "token": token_dict['token'],
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if "list" not in r.json() or len(r.json()["list"]) == 0:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_fakeid:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            user_info_dict = {'user_name': r.json()["list"][0]["nickname"],
-                              'user_id': r.json()["list"][0]["fakeid"],
-                              'avatar_url': r.json()["list"][0]["round_head_img"]}
-            return user_info_dict
-
-    # 获取腾讯视频下载链接
-    @classmethod
-    def get_tencent_video_url(cls, video_id):
-        url = 'https://vv.video.qq.com/getinfo?vids=' + str(video_id) + '&platform=101001&charge=0&otype=json'
-        response = requests.get(url=url).text.replace('QZOutputJson=', '').replace('"};', '"}')
-        response = json.loads(response)
-        url = response['vl']['vi'][0]['ul']['ui'][0]['url']
-        fvkey = response['vl']['vi'][0]['fvkey']
-        video_url = url + str(video_id) + '.mp4?vkey=' + fvkey
-        return video_url
-
-    @classmethod
-    def get_video_url(cls, article_url, env):
-        # 打印请求配置
-        ca = DesiredCapabilities.CHROME
-        ca["goog:loggingPrefs"] = {"performance": "ALL"}
-
-        # 不打开浏览器运行
-        chrome_options = webdriver.ChromeOptions()
-        chrome_options.add_argument("headless")
-        chrome_options.add_argument(
-            f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36')
-        chrome_options.add_argument("--no-sandbox")
-
-        # driver初始化
-        if env == "prod":
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
-        else:
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service(
-                '/Users/wangkun/Downloads/chromedriver/chromedriver_v113/chromedriver'))
-
-        driver.implicitly_wait(10)
-        driver.get(article_url)
-        time.sleep(1)
-
-        if len(driver.find_elements(By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]')) != 0:
-            video_url = driver.find_element(
-                By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]').get_attribute('src')
-        elif len(driver.find_elements(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]')) != 0:
-            iframe = driver.find_element(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]').get_attribute(
-                'src')
-            video_id = iframe.split('vid=')[-1].split('&')[0]
-            video_url = cls.get_tencent_video_url(video_id)
-        else:
-            video_url = 0
-        driver.quit()
-        return video_url
-
-    # 获取文章列表
-    @classmethod
-    def get_videoList(cls, log_type, crawler, rule_dict, user_dict, env):
-        mq = MQ(topic_name="topic_crawler_etl_" + env)
-        begin = 0
-        while True:
-            token_dict = cls.get_token(log_type, crawler, env)
-            url = "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=" + str(token_dict['token']) + "&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "list_ex",
-                "begin": str(begin),
-                "count": "5",
-                "fakeid": user_dict['user_id'],
-                "type": "9",
-                "query": "",
-                "token": str(token_dict['token']),
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "invalid args" and r.json()["base_resp"]["ret"] == 200002:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler,f"公众号:{user_dict['user_name']}\n抓取异常, 请检查该公众号\n")
-                return
-            if 'app_msg_list' not in r.json():
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                Common.logging(log_type, crawler, env, f"status_code:{r.status_code}, get_videoList:{r.text}\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 15)
-                continue
-            if len(r.json()['app_msg_list']) == 0:
-                Common.logger(log_type, crawler).info('没有更多视频了\n')
-                Common.logging(log_type, crawler, env, "没有更多视频了\n")
-                return
-            else:
-                begin += 5
-                app_msg_list = r.json()['app_msg_list']
-                for article in app_msg_list:
-                    try:
-                        create_time = article.get('create_time', 0)
-                        publish_time_stamp = int(create_time)
-                        publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
-                        article_url = article.get('link', '')
-                        video_dict = {
-                            'video_id': article.get('aid', ''),
-                            'video_title': article.get("title", "").replace(' ', '').replace('"', '').replace("'", ""),
-                            'publish_time_stamp': publish_time_stamp,
-                            'publish_time_str': publish_time_str,
-                            'user_name': user_dict["user_name"],
-                            'play_cnt': 0,
-                            'comment_cnt': 0,
-                            'like_cnt': 0,
-                            'share_cnt': 0,
-                            'user_id': user_dict['user_id'],
-                            'avatar_url': user_dict['avatar_url'],
-                            'cover_url': article.get('cover', ''),
-                            'article_url': article.get('link', ''),
-                            'video_url': cls.get_video_url(article_url, env),
-                            'session': f'gongzhonghao-author1-{int(time.time())}'
-                        }
-                        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 int(time.time()) - publish_time_stamp > 3600 * 24 * int(rule_dict.get('period', {}).get('max', 1000)):
-                            Common.logger(log_type, crawler).info(f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            Common.logging(log_type, crawler, env, f"发布时间超过{int(rule_dict.get('period', {}).get('max', 1000))}天\n")
-                            return
-
-                        if video_dict['article_url'] == 0 or video_dict['video_url'] == 0:
-                            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")
-                        # 标题相似度
-                        elif title_like(log_type, crawler, video_dict['video_title'], cls.platform, env) is True:
-                            Common.logger(log_type, crawler).info(f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                            Common.logging(log_type, crawler, env, f'标题相似度>=80%:{video_dict["video_title"]}\n')
-                        else:
-                            # cls.download_publish(log_type=log_type,
-                            #                      crawler=crawler,
-                            #                      video_dict=video_dict,
-                            #                      rule_dict=rule_dict,
-                            #                      # user_dict=user_dict,
-                            #                      env=env)
-                            video_dict["out_user_id"] = video_dict["user_id"]
-                            video_dict["platform"] = crawler
-                            video_dict["strategy"] = log_type
-                            video_dict["out_video_id"] = video_dict["video_id"]
-                            video_dict["width"] = 0
-                            video_dict["height"] = 0
-                            video_dict["crawler_rule"] = json.dumps(rule_dict)
-                            # video_dict["user_id"] = user_dict["uid"]
-                            video_dict["user_id"] = Publish.uids(crawler, "定向爬虫策略", "", env)
-                            video_dict["publish_time"] = video_dict["publish_time_str"]
-
-                            mq.send_msg(video_dict)
-                    except Exception as e:
-                        Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
-                        Common.logging(log_type, crawler, env, f'抓取单条视频异常:{e}\n')
-                Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                time.sleep(60)
-
-
-    @classmethod
-    def repeat_video(cls, log_type, crawler, video_id, env):
-        # sql = f""" select * from crawler_video where platform="公众号" and out_video_id="{video_id}"; """
-        sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{video_id}"; """
-        repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
-        return len(repeat_video)
-
-    # 下载/上传
-    @classmethod
-    def download_publish(cls, log_type, crawler, 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
-        # 获取视频时长
-        ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
-        video_dict["video_width"] = ffmpeg_dict["width"]
-        video_dict["video_height"] = ffmpeg_dict["height"]
-        video_dict["duration"] = ffmpeg_dict["duration"]
-        Common.logger(log_type, crawler).info(f'video_width:{video_dict["video_width"]}')
-        Common.logging(log_type, crawler, env, f'video_width:{video_dict["video_width"]}')
-        Common.logger(log_type, crawler).info(f'video_height:{video_dict["video_height"]}')
-        Common.logging(log_type, crawler, env, f'video_height:{video_dict["video_height"]}')
-        Common.logger(log_type, crawler).info(f'duration:{video_dict["duration"]}')
-        Common.logging(log_type, crawler, env, f'duration:{video_dict["duration"]}')
-        if download_rule(log_type, crawler, video_dict, rule_dict) is False:
-            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"])
-        # 保存视频信息至 "./videos/{video_title}/info.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, "开始上传视频...")
-        strategy = "定向爬虫策略"
-        if env == 'prod':
-            oss_endpoint = "inner"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
-        else:
-            oss_endpoint = "out"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{str(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,
-                                                    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}")
-        Common.logging(log_type, crawler, env, f"insert_sql:{insert_sql}")
-        MysqlHelper.update_values(log_type, crawler, insert_sql, env)
-        Common.logger(log_type, crawler).info('视频信息写入数据库成功')
-        Common.logging(log_type, crawler, env, '视频信息写入数据库成功')
-
-        # 视频写入飞书
-        Feishu.insert_columns(log_type, crawler, "47e39d", "ROWS", 1, 2)
-        # 视频ID工作表,首行写入数据
-        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,
-                   int(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['article_url'],
-                   video_dict['video_url']]]
-        time.sleep(0.5)
-        Feishu.update_values(log_type, crawler, "47e39d", "F2:Z2", values)
-        Common.logger(log_type, crawler).info('视频下载/上传成功\n')
-        Common.logging(log_type, crawler, env, '视频下载/上传成功\n')
-
-    @classmethod
-    def get_all_videos(cls, log_type, crawler, rule_dict, env):
-        while True:
-            sheetid = "Bzv72P"
-            user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
-            if user_sheet is None:
-                Common.logger(log_type, crawler).warning(f"user_sheet:{user_sheet}, 2秒后重试")
-                Common.logging(log_type, crawler, env, f"user_sheet:{user_sheet}, 2秒后重试")
-                time.sleep(2)
-                continue
-            len_sheet = len(user_sheet)
-            if len_sheet <= 461:
-                Common.logger(log_type, crawler).info("抓取用户数<=400,无需启动第五套抓取脚本\n")
-                Common.logging(log_type, crawler, env, "抓取用户数<=400,无需启动第五套抓取脚本\n")
-                return
-            # if len_sheet >= 501:
-            #     len_sheet = 501
-            for i in range(461, len_sheet):
-                user_dict = cls.get_users(log_type=log_type,
-                                          crawler=crawler,
-                                          user_sheet=user_sheet,
-                                          sheetid=sheetid,
-                                          i=i,
-                                          env=env)
-                Common.logger(log_type, crawler).info(f'获取 {user_dict["user_name"]} 公众号视频\n')
-                Common.logging(log_type, crawler, env, f'获取 {user_dict["user_name"]} 公众号视频\n')
-                try:
-                    Common.logger(log_type, crawler).info(f'获取 {user_dict["user_name"]} 公众号视频\n')
-                    Common.logging(log_type, crawler, env, f'获取 {user_dict["user_name"]} 公众号视频\n')
-                    cls.get_videoList(log_type=log_type,
-                                      crawler=crawler,
-                                      rule_dict=rule_dict,
-                                      user_dict=user_dict,
-                                      env=env)
-                    Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                    Common.logging(log_type, crawler, env, '休眠 60 秒\n')
-                    time.sleep(60)
-                except Exception as e:
-                    Common.logger(log_type, crawler).info(f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-                    Common.logging(log_type, crawler, env, f'抓取{user_dict["user_name"]}公众号时异常:{e}\n')
-            break
-
-
-if __name__ == "__main__":
-    GongzhonghaoAuthor5.get_token("author", "gongzhonghao", "dev")
-    pass

+ 0 - 0
gongzhonghao/gongzhonghao_author/gongzhonghao1_author_create_user.py → gongzhonghao/gongzhonghao_author/gongzhonghao_author_create_user.py


File diff suppressed because it is too large
+ 0 - 519
gongzhonghao/gongzhonghao_follow/gongzhonghao_follow_2.py


+ 0 - 547
gongzhonghao/gongzhonghao_follow/gongzhonghao_follow_3.py

@@ -1,547 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/3/28
-import datetime
-import difflib
-import json
-import os
-import shutil
-import sys
-import time
-from hashlib import md5
-
-import requests
-import urllib3
-# from requests.adapters import HTTPAdapter
-from selenium.webdriver import DesiredCapabilities
-from selenium.webdriver.chrome.service import Service
-from selenium.webdriver.common.by import By
-from selenium import webdriver
-
-sys.path.append(os.getcwd())
-from common.common import Common
-from common.feishu import Feishu
-from common.public import get_config_from_mysql
-from common.publish import Publish
-from common.scheduling_db import MysqlHelper
-
-
-class GongzhonghaoFollow3:
-    # 翻页参数
-    begin = 0
-    platform = "公众号"
-
-    # 基础门槛规则
-    @staticmethod
-    def download_rule(video_dict):
-        """
-        下载视频的基本规则
-        :param video_dict: 视频信息,字典格式
-        :return: 满足规则,返回 True;反之,返回 False
-        """
-        # 视频时长 20秒 - 45 分钟
-        if 60 * 45 >= int(float(video_dict['duration'])) >= 20:
-            # 宽或高
-            if int(video_dict['video_width']) >= 0 or int(video_dict['video_height']) >= 0:
-                return True
-            else:
-                return False
-        else:
-            return False
-
-    @classmethod
-    def title_like(cls, log_type, crawler, title, env):
-        select_sql = f""" select * from crawler_video where platform="公众号" """
-        video_list = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
-        if len(video_list) == 0:
-            return None
-        for video_dict in video_list:
-            video_title = video_dict["video_title"]
-            if difflib.SequenceMatcher(None, title, video_title).quick_ratio() >= 0.8:
-                return True
-            else:
-                pass
-
-    # 获取 token
-    @classmethod
-    def get_token(cls, log_type, crawler):
-        while True:
-            # try:
-            sheet = Feishu.get_values_batch(log_type, crawler, "l1VZki")
-            if sheet is None:
-                time.sleep(1)
-                continue
-            token = sheet[0][1]
-            cookie = sheet[1][1]
-            gzh_name = sheet[2][1]
-            gzh_time = sheet[3][1]
-            token_dict = {'token': token, 'cookie': cookie, 'gzh_name': gzh_name, 'gzh_time': gzh_time}
-            return token_dict
-            # except Exception as e:
-            #     Common.logger(log_type, crawler).error(f"get_cookie_token异常:{e}\n")
-
-    # 获取用户 fakeid
-    @classmethod
-    def get_fakeid(cls, log_type, crawler, user, index):
-        # try:
-        while True:
-            token_dict = cls.get_token(log_type, crawler)
-            url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=1011071554&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "search_biz",
-                "begin": "0",
-                "count": "5",
-                "query": str(user),
-                "token": token_dict['token'],
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            # s = requests.session()
-            # # max_retries=3 重试3次
-            # s.mount('http://', HTTPAdapter(max_retries=3))
-            # s.mount('https://', HTTPAdapter(max_retries=3))
-            # r = s.get(url=url, headers=headers, params=params, verify=False, proxies=Common.tunnel_proxies(), timeout=5)
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
-                Common.logger(log_type, crawler).warning(f"get_fakeid:{r.text}\n")
-                Common.logger(log_type, crawler).warning(
-                    f"公众号_3:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 过期啦\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"token_3:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 10)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
-                Common.logger(log_type, crawler).warning(f"get_fakeid:{r.text}\n")
-                Common.logger(log_type, crawler).warning(
-                    f"公众号_3:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 频控啦\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"公众号_3:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 10)
-                continue
-            if "list" not in r.json() or len(r.json()["list"]) == 0:
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
-                Common.logger(log_type, crawler).warning(f"get_fakeid:{r.text}\n")
-                Common.logger(log_type, crawler).warning(
-                    f"公众号_3:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 频控啦\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"公众号_3:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 10)
-                continue
-            fakeid = r.json()["list"][int(index) - 1]["fakeid"]
-            head_url = r.json()["list"][int(index) - 1]["round_head_img"]
-            fakeid_dict = {'fakeid': fakeid, 'head_url': head_url}
-            return fakeid_dict
-        # except Exception as e:
-        #     Common.logger(log_type, crawler).error(f"get_fakeid异常:{e}\n")
-
-    # 获取腾讯视频下载链接
-    @classmethod
-    def get_tencent_video_url(cls, video_id):
-        # try:
-        url = 'https://vv.video.qq.com/getinfo?vids=' + str(video_id) + '&platform=101001&charge=0&otype=json'
-        response = requests.get(url=url).text.replace('QZOutputJson=', '').replace('"};', '"}')
-        response = json.loads(response)
-        url = response['vl']['vi'][0]['ul']['ui'][0]['url']
-        fvkey = response['vl']['vi'][0]['fvkey']
-        video_url = url + str(video_id) + '.mp4?vkey=' + fvkey
-        return video_url
-        # except Exception as e:
-        #     Common.logger(log_type, crawler).error(f"get_tencent_video_url异常:{e}\n")
-
-    @classmethod
-    def get_video_url(cls, article_url, env):
-        # try:
-        # 打印请求配置
-        ca = DesiredCapabilities.CHROME
-        ca["goog:loggingPrefs"] = {"performance": "ALL"}
-
-        # 不打开浏览器运行
-        chrome_options = webdriver.ChromeOptions()
-        chrome_options.add_argument("headless")
-        chrome_options.add_argument(
-            f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36')
-        chrome_options.add_argument("--no-sandbox")
-
-        # driver初始化
-        if env == "prod":
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
-        else:
-            driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service(
-                '/Users/wangkun/Downloads/chromedriver/chromedriver_v111/chromedriver'))
-
-        driver.implicitly_wait(10)
-        # Common.logger(log_type, crawler).info('打开文章链接')
-        driver.get(article_url)
-        time.sleep(1)
-
-        if len(driver.find_elements(By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]')) != 0:
-            video_url = driver.find_element(
-                By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]').get_attribute('src')
-        elif len(driver.find_elements(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]')) != 0:
-            iframe = driver.find_element(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]').get_attribute(
-                'src')
-            video_id = iframe.split('vid=')[-1].split('&')[0]
-            video_url = cls.get_tencent_video_url(video_id)
-        else:
-            video_url = 0
-        driver.quit()
-        return video_url
-        # except Exception as e:
-        #     Common.logger(log_type, crawler).info(f'get_video_url异常:{e}\n')
-
-    # 获取文章列表
-    @classmethod
-    def get_videoList(cls, log_type, crawler, user, index, oss_endpoint, env):
-        # try:
-        while True:
-            fakeid_dict = cls.get_fakeid(log_type, crawler, user, index)
-            token_dict = cls.get_token(log_type, crawler)
-            url = "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-            headers = {
-                "accept": "*/*",
-                "accept-encoding": "gzip, deflate, br",
-                "accept-language": "zh-CN,zh;q=0.9",
-                "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
-                           "t=media/appmsg_edit_v2&action=edit&isNew=1"
-                           "&type=77&createType=5&token=" + str(token_dict['token']) + "&lang=zh_CN",
-                'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
-                "sec-ch-ua-mobile": "?0",
-                "sec-ch-ua-platform": '"Windows"',
-                "sec-fetch-dest": "empty",
-                "sec-fetch-mode": "cors",
-                "sec-fetch-site": "same-origin",
-                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
-                              " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
-                "x-requested-with": "XMLHttpRequest",
-                'cookie': token_dict['cookie'],
-            }
-            params = {
-                "action": "list_ex",
-                "begin": str(cls.begin),
-                "count": "5",
-                "fakeid": fakeid_dict['fakeid'],
-                "type": "9",
-                "query": "",
-                "token": str(token_dict['token']),
-                "lang": "zh_CN",
-                "f": "json",
-                "ajax": "1",
-            }
-            urllib3.disable_warnings()
-            # s = requests.session()
-            # # max_retries=3 重试3次
-            # s.mount('http://', HTTPAdapter(max_retries=3))
-            # s.mount('https://', HTTPAdapter(max_retries=3))
-            # r = s.get(url=url, headers=headers, params=params, verify=False, proxies=Common.tunnel_proxies(), timeout=5)
-            r = requests.get(url=url, headers=headers, params=params, verify=False)
-            r.close()
-            if r.json()["base_resp"]["err_msg"] == "invalid session":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
-                Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
-                Common.logger(log_type, crawler).warning(
-                    f"公众号_3:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 过期啦\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"token_3:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 10)
-                continue
-            if r.json()["base_resp"]["err_msg"] == "freq control":
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
-                Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
-                Common.logger(log_type, crawler).warning(
-                    f"公众号_3:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 频控啦\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"公众号_3:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 10)
-                continue
-            if 'app_msg_list' not in r.json():
-                Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
-                Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
-                Common.logger(log_type, crawler).warning(
-                    f"公众号_3:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 频控啦\n")
-                if 20 >= datetime.datetime.now().hour >= 10:
-                    Feishu.bot(log_type, crawler, f"公众号_3:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
-                time.sleep(60 * 10)
-                continue
-            if len(r.json()['app_msg_list']) == 0:
-                Common.logger(log_type, crawler).info('没有更多视频了\n')
-                return
-            else:
-                cls.begin += 5
-                app_msg_list = r.json()['app_msg_list']
-                for article_url in app_msg_list:
-                    # title
-                    if 'title' in article_url:
-                        title = article_url['title'].replace('/', '').replace('\n', '') \
-                            .replace('.', '').replace('“', '').replace('”', '').replace(' ', '')\
-                            .replace('"', '').replace("'", "")
-                    else:
-                        title = 0
-
-                    # aid
-                    if 'aid' in article_url:
-                        aid = article_url['aid']
-                    else:
-                        aid = 0
-
-                    # create_time
-                    if 'create_time' in article_url:
-                        create_time = article_url['create_time']
-                    else:
-                        create_time = 0
-                    publish_time_stamp = int(create_time)
-                    publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
-
-                    avatar_url = fakeid_dict['head_url']
-
-                    # cover_url
-                    if 'cover' in article_url:
-                        cover_url = article_url['cover']
-                    else:
-                        cover_url = 0
-
-                    # article_url
-                    if 'link' in article_url:
-                        article_url = article_url['link']
-                    else:
-                        article_url = 0
-
-                    video_url = cls.get_video_url(article_url, env)
-
-                    video_dict = {
-                        'video_id': aid,
-                        'video_title': title,
-                        'publish_time_stamp': publish_time_stamp,
-                        'publish_time_str': publish_time_str,
-                        'user_name': user,
-                        'play_cnt': 0,
-                        'comment_cnt': 0,
-                        'like_cnt': 0,
-                        'share_cnt': 0,
-                        'user_id': fakeid_dict['fakeid'],
-                        'avatar_url': avatar_url,
-                        'cover_url': cover_url,
-                        'article_url': article_url,
-                        'video_url': video_url,
-                        'session': f'gongzhonghao-follow-{int(time.time())}'
-                    }
-                    for k, v in video_dict.items():
-                        Common.logger(log_type, crawler).info(f"{k}:{v}")
-                    if int(time.time()) - publish_time_stamp >= 3600 * 24 * 3:
-                        Common.logger(log_type, crawler).info(f'发布时间{publish_time_str} > 3 天\n')
-                        cls.begin = 0
-                        return
-                    cls.download_publish(log_type, crawler, video_dict, oss_endpoint, env)
-
-                Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                time.sleep(60)
-        # except Exception as e:
-        #     Common.logger(log_type, crawler).error("get_videoList异常:{}\n", e)
-
-    @classmethod
-    def repeat_video(cls, log_type, crawler, video_id, env):
-        sql = f""" select * from crawler_video where platform="公众号" and out_video_id="{video_id}"; """
-        repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
-        return len(repeat_video)
-
-    # 下载/上传
-    @classmethod
-    def download_publish(cls, log_type, crawler, video_dict, oss_endpoint, env):
-        # try:
-        if video_dict['article_url'] == 0 or video_dict['video_url'] == 0:
-            Common.logger(log_type, crawler).info("文章涉嫌违反相关法律法规和政策\n")
-        # 标题敏感词过滤
-        elif any(word if 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")
-        # 已下载判断
-        elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env) != 0:
-            Common.logger(log_type, crawler).info("视频已下载\n")
-        # 标题相似度
-        elif cls.title_like(log_type, crawler, video_dict['video_title'], env) is True:
-            Common.logger(log_type, crawler).info(f'标题相似度>=80%:{video_dict["video_title"]}\n')
-        else:
-            # 下载视频
-            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()
-            # 获取视频时长
-            ffmpeg_dict = Common.ffmpeg(log_type, crawler,
-                                        f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
-            if ffmpeg_dict is None:
-                # 删除视频文件夹
-                shutil.rmtree(f"./{crawler}/videos/{md_title}")
-                Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
-                return
-            video_dict["video_width"] = ffmpeg_dict["width"]
-            video_dict["video_height"] = ffmpeg_dict["height"]
-            video_dict["duration"] = ffmpeg_dict["duration"]
-            video_size = ffmpeg_dict["size"]
-            Common.logger(log_type, crawler).info(f'video_width:{video_dict["video_width"]}')
-            Common.logger(log_type, crawler).info(f'video_height:{video_dict["video_height"]}')
-            Common.logger(log_type, crawler).info(f'duration:{video_dict["duration"]}')
-            Common.logger(log_type, crawler).info(f'video_size:{video_size}')
-            # 视频size=0,直接删除
-            if int(video_size) == 0 or cls.download_rule(video_dict) is False:
-                # 删除视频文件夹
-                shutil.rmtree(f"./{crawler}/videos/{md_title}")
-                Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
-                return
-            # 下载封面
-            Common.download_method(log_type=log_type, crawler=crawler, text="cover",
-                                   title=video_dict["video_title"], url=video_dict["cover_url"])
-            # 保存视频信息至 "./videos/{video_title}/info.txt"
-            Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
-
-            # 上传视频
-            Common.logger(log_type, crawler).info("开始上传视频...")
-            strategy = "定向爬虫策略"
-            our_video_id = Publish.upload_and_publish(log_type=log_type,
-                                                      crawler=crawler,
-                                                      strategy=strategy,
-                                                      our_uid="follow",
-                                                      oss_endpoint=oss_endpoint,
-                                                      env=env)
-            if env == 'prod':
-                our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
-            else:
-                our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
-            Common.logger(log_type, crawler).info("视频上传完成")
-
-            if our_video_id is None:
-                # 删除视频文件夹
-                shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
-                return
-
-            # 视频信息保存数据库
-            rule_dict = {
-                "duration": {"min": 20, "max": 45 * 60},
-                "publish_day": {"min": 3}
-            }
-
-            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)
-            Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
-
-            # 视频写入飞书
-            Feishu.insert_columns(log_type, crawler, "47e39d", "ROWS", 1, 2)
-            # 视频ID工作表,首行写入数据
-            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,
-                       int(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['article_url'],
-                       video_dict['video_url']]]
-            time.sleep(0.5)
-            Feishu.update_values(log_type, crawler, "47e39d", "F2:Z2", values)
-            Common.logger(log_type, crawler).info('视频下载/上传成功\n')
-        # except Exception as e:
-        #     Common.logger(log_type, crawler).error(f"download_publish异常:{e}\n")
-
-    @classmethod
-    def get_users(cls):
-        # user_sheet = Feishu.get_values_batch("follow", 'gongzhonghao', 'Bzv72P')
-        # user_list = []
-        # for i in range(81, len(user_sheet)):
-        #     user_name = user_sheet[i][0]
-        #     index = user_sheet[i][1]
-        #     user_dict = {
-        #         "user_name": user_name,
-        #         "index": index,
-        #     }
-        #     user_list.append(user_dict)
-        # print(len(user_list))
-        # print(user_list)
-
-        user_list = [{'user_name': '方敏爱美食', 'index': 1}, {'user_name': '针灸推拿特色技术', 'index': 1}, {'user_name': '挺进天山', 'index': 1}, {'user_name': '紫陌捻花', 'index': 1}, {'user_name': '巨响养身', 'index': 1}, {'user_name': '荣观世界', 'index': 1}, {'user_name': 'Music音乐世界', 'index': 1}, {'user_name': '微观调查组', 'index': 1}, {'user_name': '用汉方拥抱世界', 'index': 1}, {'user_name': '医学养身秘诀', 'index': 1}, {'user_name': '医学老人养身', 'index': 1}, {'user_name': '热文微观', 'index': 1}, {'user_name': '医学养身秘笈', 'index': 1}, {'user_name': '你未读消息', 'index': 1}, {'user_name': '零点相聚', 'index': 2}, {'user_name': '观念颠覆一切', 'index': 1}, {'user_name': '侯老师说食疗精选', 'index': 1}, {'user_name': '侯老师说食疗', 'index': 1}, {'user_name': '今日看点收集', 'index': 1}, {'user_name': '君拍', 'index': 1}, {'user_name': '惊爆视频', 'index': 3}, {'user_name': '绝美生活', 'index': 2}, {'user_name': '新龙虎局势', 'index': 1}, {'user_name': '行走的足音', 'index': 1}, {'user_name': '月光下小夜曲', 'index': 1}, {'user_name': '罪与罚的言', 'index': 1}, {'user_name': '祝福音画', 'index': 1}, {'user_name': '这年头儿', 'index': 1}, {'user_name': '祝福励志正能量', 'index': 1}, {'user_name': '出借人清查组', 'index': 1}, {'user_name': '强哥来了', 'index': 1}, {'user_name': '绝美相册', 'index': 1}, {'user_name': '绝美立体相册', 'index': 1}, {'user_name': '生活美相册', 'index': 1}, {'user_name': '祝您生活幸福', 'index': 1}, {'user_name': '完美生活', 'index': 3}, {'user_name': '新龙虎局世', 'index': 1}, {'user_name': '精美音画相册', 'index': 1}, {'user_name': '音画场景', 'index': 1}, {'user_name': '出借人投诉处', 'index': 1}]
-        return user_list
-
-    @classmethod
-    def get_all_videos(cls, log_type, crawler, oss_endpoint, env):
-        user_list = cls.get_users()
-        for user_dict in user_list:
-            try:
-                user_name = user_dict['user_name']
-                index = user_dict['index']
-                Common.logger(log_type, crawler).info(f'获取 {user_name} 公众号视频\n')
-                cls.get_videoList(log_type, crawler, user_name, index, oss_endpoint, env)
-                cls.begin = 0
-                Common.logger(log_type, crawler).info('休眠 60 秒\n')
-                time.sleep(60)
-            except Exception as e:
-                Common.logger(log_type, crawler).info(f'get_all_videos异常:{e}\n')
-
-
-if __name__ == "__main__":
-    GongzhonghaoFollow3.get_users()
-    # GongzhonghaoFollow.get_users()
-    # GongzhonghaoFollow.get_videoList(log_type="follow",
-    #                                  crawler="gongzhonghao",
-    #                                  user="香音难忘",
-    #                                  index=1,
-    #                                  oss_endpoint="out",
-    #                                  env="dev")
-    pass

+ 0 - 108
gongzhonghao/gongzhonghao_main/run_gzh1_author.py

@@ -1,108 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/6/6
-import argparse
-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.public import task_fun_mq, get_consumer, ack_message
-from common.common import Common
-from gongzhonghao.gongzhonghao_author.gongzhonghao1_author import GongzhonghaoAuthor1
-
-
-def main(log_type, crawler, topic_name, group_id, env):
-    if "gzh1" in topic_name:
-        log_type = "author1"
-    elif "gzh2" in topic_name:
-        log_type = "author2"
-    elif "gzh3" in topic_name:
-        log_type = "author3"
-    elif "gzh4" in topic_name:
-        log_type = "author4"
-    elif "gzh5" in topic_name:
-        log_type = "author5"
-    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']
-                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}\n")
-                Common.logging(log_type, crawler, env, f"抓取规则:{rule_dict}\n")
-                Common.logger(log_type, crawler).info(f'开始抓取:{task_dict["taskName"]}\n')
-                Common.logging(log_type, crawler, env, f'开始抓取:{task_dict["taskName"]}\n')
-                GongzhonghaoAuthor1.get_all_videos(log_type=log_type,
-                                                    crawler=crawler,
-                                                    rule_dict=rule_dict,
-                                                    env=env)
-                Common.del_logs(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)

+ 0 - 32
gongzhonghao/gongzhonghao_main/run_gzh1_author_dev.py

@@ -1,32 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/6/20
-import os
-import sys
-sys.path.append(os.getcwd())
-from common.common import Common
-# from gongzhonghao.gongzhonghao_author.gongzhonghao1_author import GongzhonghaoAuthor1
-# from gongzhonghao.gongzhonghao_author.gongzhonghao2_author import GongzhonghaoAuthor2
-# from gongzhonghao.gongzhonghao_author.gongzhonghao3_author import GongzhonghaoAuthor3
-# from gongzhonghao.gongzhonghao_author.gongzhonghao4_author import GongzhonghaoAuthor4
-from gongzhonghao.gongzhonghao_author.gongzhonghao5_author import GongzhonghaoAuthor5
-
-
-def gzh_main(log_type, crawler, env):
-    Common.logger(log_type, crawler).info("开始抓取:公众号")
-    Common.logging(log_type, crawler, env, "开始抓取:公众号")
-    # GongzhonghaoAuthor1.get_all_videos(log_type=log_type,
-    # GongzhonghaoAuthor2.get_all_videos(log_type=log_type,
-    # GongzhonghaoAuthor3.get_all_videos(log_type=log_type,
-    # GongzhonghaoAuthor4.get_all_videos(log_type=log_type,
-    GongzhonghaoAuthor5.get_all_videos(log_type=log_type,
-                                       crawler=crawler,
-                                       rule_dict={"period": {"max": 1, "min": 1}, "duration": {"max": 2700, "min": 20}},
-                                       env=env)
-    Common.del_logs(log_type, crawler)
-    Common.logger(log_type, crawler).info('抓取一轮结束\n')
-    Common.logging(log_type, crawler, env, '抓取一轮结束\n')
-
-
-if __name__ == "__main__":
-    gzh_main(log_type="author", crawler="gongzhonghao", env="dev")

+ 0 - 108
gongzhonghao/gongzhonghao_main/run_gzh2_author.py

@@ -1,108 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/6/6
-import argparse
-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.public import task_fun_mq, get_consumer, ack_message
-from common.common import Common
-from gongzhonghao.gongzhonghao_author.gongzhonghao2_author import GongzhonghaoAuthor2
-
-
-def main(log_type, crawler, topic_name, group_id, env):
-    if "gzh1" in topic_name:
-        log_type = "author1"
-    elif "gzh2" in topic_name:
-        log_type = "author2"
-    elif "gzh3" in topic_name:
-        log_type = "author3"
-    elif "gzh4" in topic_name:
-        log_type = "author4"
-    elif "gzh5" in topic_name:
-        log_type = "author5"
-    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']
-                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}\n")
-                Common.logging(log_type, crawler, env, f"抓取规则:{rule_dict}\n")
-                Common.logger(log_type, crawler).info(f'开始抓取:{task_dict["taskName"]}\n')
-                Common.logging(log_type, crawler, env, f'开始抓取:{task_dict["taskName"]}\n')
-                GongzhonghaoAuthor2.get_all_videos(log_type=log_type,
-                                                    crawler=crawler,
-                                                    rule_dict=rule_dict,
-                                                    env=env)
-                Common.del_logs(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)

+ 0 - 110
gongzhonghao/gongzhonghao_main/run_gzh3_author.py

@@ -1,110 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/6/6
-import argparse
-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.public import task_fun_mq, get_consumer, ack_message
-from common.common import Common
-from gongzhonghao.gongzhonghao_author.gongzhonghao3_author import GongzhonghaoAuthor3
-
-
-def main(log_type, crawler, topic_name, group_id, env):
-    if "gzh1" in topic_name:
-        log_type = "author1"
-    elif "gzh2" in topic_name:
-        log_type = "author2"
-    elif "gzh3" in topic_name:
-        log_type = "author3"
-    elif "gzh4" in topic_name:
-        log_type = "author4"
-    elif "gzh5" in topic_name:
-        log_type = "author5"
-    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
-                Common.logger(log_type, crawler).info("回传 ack 消息")
-                ack_message(log_type=log_type, crawler=crawler, recv_msgs=recv_msgs, consumer=consumer)
-                time.sleep(2)
-
-                # 处理爬虫业务
-                task_dict = task_fun_mq(msg.message_body)['task_dict']
-                rule_dict = task_fun_mq(msg.message_body)['rule_dict']
-                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}\n")
-                Common.logging(log_type, crawler, env, f"抓取规则:{rule_dict}\n")
-                Common.logger(log_type, crawler).info(f'开始抓取:{task_dict["taskName"]}\n')
-                Common.logging(log_type, crawler, env, f'开始抓取:{task_dict["taskName"]}\n')
-                GongzhonghaoAuthor3.get_all_videos(log_type=log_type,
-                                                    crawler=crawler,
-                                                    rule_dict=rule_dict,
-                                                    env=env)
-                Common.del_logs(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)

+ 0 - 108
gongzhonghao/gongzhonghao_main/run_gzh4_author.py

@@ -1,108 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/6/6
-import argparse
-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.public import task_fun_mq, get_consumer, ack_message
-from common.common import Common
-from gongzhonghao.gongzhonghao_author.gongzhonghao4_author import GongzhonghaoAuthor4
-
-
-def main(log_type, crawler, topic_name, group_id, env):
-    if "gzh1" in topic_name:
-        log_type = "author1"
-    elif "gzh2" in topic_name:
-        log_type = "author2"
-    elif "gzh3" in topic_name:
-        log_type = "author3"
-    elif "gzh4" in topic_name:
-        log_type = "author4"
-    elif "gzh5" in topic_name:
-        log_type = "author5"
-    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']
-                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}\n")
-                Common.logging(log_type, crawler, env, f"抓取规则:{rule_dict}\n")
-                Common.logger(log_type, crawler).info(f'开始抓取:{task_dict["taskName"]}\n')
-                Common.logging(log_type, crawler, env, f'开始抓取:{task_dict["taskName"]}\n')
-                GongzhonghaoAuthor4.get_all_videos(log_type=log_type,
-                                                    crawler=crawler,
-                                                    rule_dict=rule_dict,
-                                                    env=env)
-                Common.del_logs(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)

+ 0 - 108
gongzhonghao/gongzhonghao_main/run_gzh5_author.py

@@ -1,108 +0,0 @@
-# -*- coding: utf-8 -*-
-# @Author: wangkun
-# @Time: 2023/6/6
-import argparse
-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.public import task_fun_mq, get_consumer, ack_message
-from common.common import Common
-from gongzhonghao.gongzhonghao_author.gongzhonghao5_author import GongzhonghaoAuthor5
-
-
-def main(log_type, crawler, topic_name, group_id, env):
-    if "gzh1" in topic_name:
-        log_type = "author1"
-    elif "gzh2" in topic_name:
-        log_type = "author2"
-    elif "gzh3" in topic_name:
-        log_type = "author3"
-    elif "gzh4" in topic_name:
-        log_type = "author4"
-    elif "gzh5" in topic_name:
-        log_type = "author5"
-    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']
-                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}\n")
-                Common.logging(log_type, crawler, env, f"抓取规则:{rule_dict}\n")
-                Common.logger(log_type, crawler).info(f'开始抓取:{task_dict["taskName"]}\n')
-                Common.logging(log_type, crawler, env, f'开始抓取:{task_dict["taskName"]}\n')
-                GongzhonghaoAuthor5.get_all_videos(log_type=log_type,
-                                                    crawler=crawler,
-                                                    rule_dict=rule_dict,
-                                                    env=env)
-                Common.del_logs(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)

+ 6 - 1
gongzhonghao/gongzhonghao_main/run_gzh_author.py

@@ -14,6 +14,7 @@ from gongzhonghao.gongzhonghao_author.gongzhonghao_author import GongzhonghaoAut
 
 
 def get_author_videos(log_type, crawler, token_index, task_dict, rule_dict, user_list, env):
+    gongzhonghao_author_start_time = int(time.time())
     Common.logger(log_type, crawler).info(f'开始抓取:{task_dict["taskName"]}\n')
     Common.logging(log_type, crawler, env, f'开始抓取:{task_dict["taskName"]}\n')
     Common.logger(log_type, crawler).info(f"user_list:{user_list}")
@@ -25,9 +26,13 @@ def get_author_videos(log_type, crawler, token_index, task_dict, rule_dict, user
                                       rule_dict=rule_dict,
                                       user_list=user_list,
                                       env=env)
-    Common.del_logs(log_type, crawler)
+    # Common.del_logs(log_type, crawler)
     Common.logger(log_type, crawler).info('抓取一轮结束\n')
     Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+    gongzhonghao_author_end_time = int(time.time())
+    gongzhonghao_author_duration = gongzhonghao_author_start_time - gongzhonghao_author_end_time
+    Common.logger(log_type, crawler).info(f"duration {gongzhonghao_author_duration}")
+    Common.logging(log_type, crawler, env, f"duration {gongzhonghao_author_duration}")
 
 
 def main(log_type, crawler, topic_name, group_id, env):

+ 6 - 1
kuaishou/kuaishou_main/run_ks_author.py

@@ -32,6 +32,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                kuaishou_author_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -73,9 +74,13 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                            rule_dict=rule_dict,
                                                            user_list=user_list,
                                                            env=env)
-                Common.del_logs(log_type, crawler)
+                # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+                kuaishou_author_end_time = int(time.time())
+                kuaishou_author_duration = kuaishou_author_start_time - kuaishou_author_end_time
+                Common.logger(log_type, crawler).info(f"duration {kuaishou_author_duration}")
+                Common.logging(log_type, crawler, env, f"duration {kuaishou_author_duration}")
 
         except MQExceptionBase as err:
             # Topic中没有消息可消费。

+ 6 - 1
kuaishou/kuaishou_main/run_ks_recommend.py

@@ -33,6 +33,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                kuaishou_recommend_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -78,9 +79,13 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                           rule_dict=rule_dict,
                                                           our_uid=our_uid,
                                                           env=env)
-                Common.del_logs(log_type, crawler)
+                # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+                kuaishou_recommend_end_time = int(time.time())
+                kuaishou_recommend_duration = kuaishou_recommend_start_time - kuaishou_recommend_end_time
+                Common.logger(log_type, crawler).info(f"duration {kuaishou_recommend_duration}")
+                Common.logging(log_type, crawler, env, f"duration {kuaishou_recommend_duration}")
 
         except MQExceptionBase as err:
             # Topic中没有消息可消费。

+ 28 - 1
suisuiniannianyingfuqi/suisuiniannianyingfuqi_main/run_ssnnyfq_recommend.py

@@ -25,11 +25,16 @@ def main(log_type, crawler, topic_name, group_id, env):
                                           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:
+                ssnnyfq_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -40,6 +45,16 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                       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)
 
@@ -54,9 +69,13 @@ def main(log_type, crawler, topic_name, group_id, env):
                     our_uid_list.append(user["uid"])
                 our_uid = random.choice(our_uid_list)
                 Common.logger(log_type, crawler).info(f"调度任务:\n{task_dict}")
+                Common.logging(log_type, crawler, env, f"调度任务:\n{task_dict}")
                 Common.logger(log_type, crawler).info(f"抓取规则:\n{rule_dict}")
+                Common.logging(log_type, crawler, env, f"抓取规则:\n{rule_dict}")
                 Common.logger(log_type, crawler).info(f"用户列表:\n{user_list}")
+                Common.logging(log_type, crawler, env, f"用户列表:\n{user_list}")
                 Common.logger(log_type, crawler).info(f'开始抓取:{task_dict["taskName"]}\n')
+                Common.logging(log_type, crawler, env, f'开始抓取:{task_dict["taskName"]}\n')
                 SuisuiniannianyingfuqiRecommendScheduling.get_videoList(log_type=log_type,
                                                                         crawler=crawler,
                                                                         our_uid=our_uid,
@@ -64,17 +83,25 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                                         env=env)
                 Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
+                Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+                ssnnyfq_end_time = int(time.time())
+                ssnnyfq_duration = ssnnyfq_start_time - ssnnyfq_end_time
+                Common.logger(log_type, crawler).info(f"duration {ssnnyfq_duration}")
+                Common.logging(log_type, crawler, env, f"duration {ssnnyfq_duration}")
 
         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)  ## 添加参数,注明参数类型
@@ -87,4 +114,4 @@ if __name__ == "__main__":
          crawler=args.crawler,
          topic_name=args.topic_name,
          group_id=args.group_id,
-         env=args.env)
+         env=args.env)

+ 9 - 7
suisuiniannianyingfuqi/suisuiniannianyingfuqi_recommend/suisuiniannianyingfuqi_recommend_scheduling.py

@@ -64,12 +64,15 @@ class SuisuiniannianyingfuqiRecommendScheduling:
                 page += 1
                 if response.status_code != 200:
                     Common.logger(log_type, crawler).warning(f'get_videoList:{response.status_code}, {response.text}\n')
+                    Common.logging(log_type, crawler, env, f'get_videoList:{response.status_code}, {response.text}\n')
                     return
                 elif 'data' not in response.json():
                     Common.logger(log_type, crawler).warning(f'get_videoList:{response.status_code}, {response.json()}\n')
+                    Common.logging(log_type, crawler, env, f'get_videoList:{response.status_code}, {response.text}\n')
                     return
                 elif len(response.json()['data']['video_list']['data']) == 0:
                     Common.logger(log_type, crawler).info(f'没有更多数据啦~ {response.json()}\n')
+                    Common.logging(log_type, crawler, env, f'没有更多数据啦~ {response.json()}\n')
                     return
                 else:
                     feeds = response.json()['data']['video_list']['data']
@@ -93,20 +96,18 @@ class SuisuiniannianyingfuqiRecommendScheduling:
                                           'session': f"suisuiniannianyingfuqi-{int(time.time())}"}
                             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["cover_url"] == '' 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 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)
                                 video_dict["out_user_id"] = video_dict["user_id"]
                                 video_dict["platform"] = crawler
                                 video_dict["strategy"] = log_type
@@ -116,12 +117,13 @@ class SuisuiniannianyingfuqiRecommendScheduling:
                                 video_dict["crawler_rule"] = json.dumps(rule_dict)
                                 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)
                         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

+ 6 - 1
xiaoniangao/xiaoniangao_main/run_xng_author.py

@@ -32,6 +32,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                xng_author_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -74,9 +75,13 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                               user_list=user_list,
                                                               rule_dict=rule_dict,
                                                               env=env)
-                Common.del_logs(log_type, crawler)
+                # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+                xng_author_end_time = int(time.time())
+                xng_author_duration = xng_author_start_time - xng_author_end_time
+                Common.logger(log_type, crawler).info(f"duration {xng_author_duration}")
+                Common.logging(log_type, crawler, env, f"duration {xng_author_duration}")
 
         except MQExceptionBase as err:
             # Topic中没有消息可消费。

+ 8 - 1
xiaoniangao/xiaoniangao_main/run_xng_hour.py

@@ -4,6 +4,8 @@
 import argparse
 import datetime
 import random
+import time
+
 from mq_http_sdk.mq_client import *
 from mq_http_sdk.mq_consumer import *
 from mq_http_sdk.mq_exception import MQExceptionBase
@@ -34,6 +36,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                xng_hour_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -109,9 +112,13 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                                rule_dict=rule_dict,
                                                                our_uid=our_uid,
                                                                env=env)
-                Common.del_logs(log_type, crawler)
+                # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+                xng_hour_end_time = int(time.time())
+                xng_hour_duration = xng_hour_start_time - xng_hour_end_time
+                Common.logger(log_type, crawler).info(f"duration {xng_hour_duration}")
+                Common.logging(log_type, crawler, env, f"duration {xng_hour_duration}")
 
         except MQExceptionBase as err:
             # Topic中没有消息可消费。

+ 6 - 2
xiaoniangao/xiaoniangao_main/run_xng_play.py

@@ -33,6 +33,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                xng_play_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -78,10 +79,13 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                         rule_dict=rule_dict,
                                                         our_uid=our_uid,
                                                         env=env)
-                Common.del_logs(log_type, crawler)
+                # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
-
+                xng_play_end_time = int(time.time())
+                xng_play_duration = xng_play_start_time - xng_play_end_time
+                Common.logger(log_type, crawler).info(f"duration {xng_play_duration}")
+                Common.logging(log_type, crawler, env, f"duration {xng_play_duration}")
         except MQExceptionBase as err:
             # Topic中没有消息可消费。
             if err.type == "MessageNotExist":

+ 5 - 0
xigua/xigua_main/run_xg_author.py

@@ -32,6 +32,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                xg_author_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -76,6 +77,10 @@ def main(log_type, crawler, topic_name, group_id, env):
                 Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+                xg_author_end_time = int(time.time())
+                xg_author_duration = xg_author_start_time - xg_author_end_time
+                Common.logger(log_type, crawler).info(f"duration {xg_author_duration}")
+                Common.logging(log_type, crawler, env, f"duration {xg_author_duration}")
 
         except MQExceptionBase as err:
             # Topic中没有消息可消费。

+ 5 - 1
xigua/xigua_main/run_xg_recommend.py

@@ -36,6 +36,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                xg_recommend_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -85,7 +86,10 @@ def main(log_type, crawler, topic_name, group_id, env):
                 # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
-
+                xg_recommend_end_time = int(time.time())
+                xg_recommend_duration = xg_recommend_start_time - xg_recommend_end_time
+                Common.logger(log_type, crawler).info(f"duration {xg_recommend_duration}")
+                Common.logging(log_type, crawler, env, f"duration {xg_recommend_duration}")
         except MQExceptionBase as err:
             # Topic中没有消息可消费。
             if err.type == "MessageNotExist":

+ 6 - 1
xigua/xigua_main/run_xg_search.py

@@ -32,6 +32,7 @@ def main(log_type, crawler, topic_name, group_id, env):
             # 长轮询消费消息。
             recv_msgs = consumer.consume_message(batch, wait_seconds)
             for msg in recv_msgs:
+                xg_search_start_time = int(time.time())
                 Common.logger(log_type, crawler).info(f"Receive\n"
                                                       f"MessageId:{msg.message_id}\n"
                                                       f"MessageBodyMD5:{msg.message_body_md5}\n"
@@ -75,9 +76,13 @@ def main(log_type, crawler, topic_name, group_id, env):
                                                         env=env)
                 os.system("ps aux | grep Chrome | grep -v grep | awk '{print $2}' | xargs kill -9")
                 os.system("ps aux | grep chromedriver | grep -v grep | awk '{print $2}' | xargs kill -9")
-                Common.del_logs(log_type, crawler)
+                # Common.del_logs(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')
+                xg_search_end_time = int(time.time())
+                xg_search_duration = xg_search_start_time - xg_search_end_time
+                Common.logger(log_type, crawler).info(f"duration {xg_search_duration}")
+                Common.logging(log_type, crawler, env, f"duration {xg_search_duration}")
 
         except MQExceptionBase as err:
             # Topic中没有消息可消费。

Some files were not shown because too many files changed in this diff