Browse Source

Merge branch 'master' into wangkun

wangkun 2 years ago
parent
commit
f0125b8cc4

+ 7 - 0
README.MD

@@ -159,6 +159,13 @@ cd ~ && source ./base_profile && ps aux | grep weixinzhishu | grep -v grep | awk
 ```
 
 
+#### 抖音
+```commandline
+阿里云 102 服务器
+sh ./main/main.sh ./douyin/douyin_main/run_douyin_recommend.py --log_type="recommend" --crawler="douyin" --strategy="推荐爬虫策略" --oss_endpoint="inner" --env="prod" --machine="aliyun" douyin/recommend.log
+# sh ./main/main.sh ./kuaishou/douyin_main/run_douyin_recommend.py --log_type="recommend" --crawler="douyin" --strategy="定向爬策策略" --env="prod" --machine="aliyun" kuaishou/nohup.log
+本机
+
 #### 爬虫进程监测
 ```commandline
 阿里云 102 服务器:/usr/bin/sh /data5/piaoquan_crawler/main/process.sh "prod"

+ 12 - 0
douyin/douyin_recommend/__init__.py

@@ -1,3 +1,15 @@
+import execjs
+import os
 
 
+def get_xb(f_url, ua):
+    js_path = os.path.abspath(os.path.dirname(os.getcwd()))
+    with open(f'{js_path}/xb.js', 'r', encoding='utf-8') as f:
+        douyin_js = f.read()
 
+    params = f_url.split('/?')[1]
+    # params = urllib.parse.unquote(params)
+    # params = urllib.parse.unquote(urllib.parse.urlencode(params, safe='='))
+    ctx = execjs.compile(douyin_js)
+    xb = ctx.call('_0x11bbd8', params, ua)
+    return xb

BIN
douyin/douyin_recommend/douyin/.DS_Store


+ 27 - 17
douyin/douyin_recommend/recommend_dy.py

@@ -3,34 +3,21 @@
 # @Time: 2023/4/06
 import json
 import os
+import random
 import shutil
 import sys
 import time
 import requests
-import execjs
 from hashlib import md5
-
+from douyin.douyin_recommend import get_xb
 sys.path.append(os.getcwd())
 from common.db import MysqlHelper
 from common.feishu import Feishu
 from common.publish import Publish
-from common.public import get_user_from_mysql
 from common.userAgent import get_random_user_agent
 from common.common import Common
 
 
-def get_xb(f_url, ua):
-    with open('../xb.js', 'r', encoding='utf-8') as f:
-        douyin_js = f.read()
-
-    params = f_url.split('/?')[1]
-    # params = urllib.parse.unquote(params)
-    # params = urllib.parse.unquote(urllib.parse.urlencode(params, safe='='))
-    ctx = execjs.compile(douyin_js)
-    xb = ctx.call('_0x11bbd8', params, ua)
-    return xb
-
-
 class DyRecommend(object):
     # 个人主页视频翻页参数
     # offset = 0
@@ -103,6 +90,25 @@ class DyRecommend(object):
         except Exception as e:
             Common.logger(log_type, crawler).error(f'filter_words异常:{e}\n')
 
+    @classmethod
+    def random_title(cls, log_type, crawler):
+        try:
+            while True:
+                random_title_sheet = Feishu.get_values_batch(log_type, crawler, 'sPK2oY')
+                if random_title_sheet is None:
+                    Common.logger(log_type, crawler).warning(f"filter_words_sheet:{random_title_sheet} 10秒钟后重试")
+                    continue
+                random_title_list = []
+                for x in random_title_sheet:
+                    for y in x:
+                        if y is None:
+                            pass
+                        else:
+                            random_title_list.append(y)
+                return random.choice(random_title_list)
+        except Exception as e:
+            Common.logger(log_type, crawler).error(f'random_title:{e}\n')
+
     @classmethod
     def get_videolist(cls, log_type, crawler, strategy, our_id, oss_endpoint, env, machine):
         rule_dict = cls.get_rule(log_type, crawler)
@@ -130,8 +136,12 @@ class DyRecommend(object):
                     publish_time = info['create_time']
                     publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time))
                     publish_day = int((int(time.time()) - publish_time) / (3600 * 24))
+                    if not info['desc']:
+                        video_title = cls.random_title(log_type, crawler)
+                    else:
+                        video_title = info['desc']
 
-                    video_dict = {'video_title': info['desc'],
+                    video_dict = {'video_title': video_title,
                                   'video_id': info['aweme_id'],
                                   'play_cnt': info['statistics']['play_count'],
                                   'comment_cnt': info['statistics']['comment_count'],
@@ -225,7 +235,7 @@ class DyRecommend(object):
                     return
 
                 # 视频写入飞书
-                # Feishu.insert_columns(log_type, 'douyin', "82c8d9", "ROWS", 1, 2)
+                Feishu.insert_columns(log_type, 'douyin', "82c8d9", "ROWS", 1, 2)
                 upload_time = int(time.time())
                 values = [[
                     our_video_id,

+ 258 - 264
kuaishou/kuaishou_follow/kuaishou_follow.py

@@ -31,38 +31,33 @@ class KuaiShouFollow:
     @classmethod
     def get_rule(cls, log_type, crawler, index):
         try:
-            while True:
-                rule_sheet = Feishu.get_values_batch(log_type, crawler, "3iqG4z")
-                if rule_sheet is None:
-                    Common.logger(log_type, crawler).warning("rule_sheet is None! 10秒后重新获取")
-                    time.sleep(10)
-                    continue
-                if index == 1:
-                    rule_dict = {
-                        "play_cnt": f"{rule_sheet[1][1]}{rule_sheet[1][2]}",
-                        "video_width": f"{rule_sheet[2][1]}{rule_sheet[2][2]}",
-                        "video_height": f"{rule_sheet[3][1]}{rule_sheet[3][2]}",
-                        "like_cnt": f"{rule_sheet[4][1]}{rule_sheet[4][2]}",
-                        "duration": f"{rule_sheet[5][1]}{rule_sheet[5][2]}",
-                        "download_cnt": f"{rule_sheet[6][1]}{rule_sheet[6][2]}",
-                        "publish_time": f"{rule_sheet[7][1]}{rule_sheet[7][2]}",
-                    }
-                    # for k, v in rule_dict.items():
-                    #     Common.logger(log_type, crawler).info(f"{k}:{v}")
-                    return rule_dict
-                elif index == 2:
-                    rule_dict = {
-                        "play_cnt": f"{rule_sheet[9][1]}{rule_sheet[9][2]}",
-                        "video_width": f"{rule_sheet[10][1]}{rule_sheet[10][2]}",
-                        "video_height": f"{rule_sheet[11][1]}{rule_sheet[11][2]}",
-                        "like_cnt": f"{rule_sheet[12][1]}{rule_sheet[12][2]}",
-                        "duration": f"{rule_sheet[13][1]}{rule_sheet[13][2]}",
-                        "download_cnt": f"{rule_sheet[14][1]}{rule_sheet[14][2]}",
-                        "publish_time": f"{rule_sheet[15][1]}{rule_sheet[15][2]}",
-                    }
-                    # for k, v in rule_dict.items():
-                    #     Common.logger(log_type, crawler).info(f"{k}:{v}")
-                    return rule_dict
+            rule_sheet = Feishu.get_values_batch(log_type, crawler, "3iqG4z")
+            if index == 1:
+                rule_dict = {
+                    "play_cnt": f"{rule_sheet[1][1]}{rule_sheet[1][2]}",
+                    "video_width": f"{rule_sheet[2][1]}{rule_sheet[2][2]}",
+                    "video_height": f"{rule_sheet[3][1]}{rule_sheet[3][2]}",
+                    "like_cnt": f"{rule_sheet[4][1]}{rule_sheet[4][2]}",
+                    "duration": f"{rule_sheet[5][1]}{rule_sheet[5][2]}",
+                    "download_cnt": f"{rule_sheet[6][1]}{rule_sheet[6][2]}",
+                    "publish_time": f"{rule_sheet[7][1]}{rule_sheet[7][2]}",
+                }
+                # for k, v in rule_dict.items():
+                #     Common.logger(log_type, crawler).info(f"{k}:{v}")
+                return rule_dict
+            elif index == 2:
+                rule_dict = {
+                    "play_cnt": f"{rule_sheet[9][1]}{rule_sheet[9][2]}",
+                    "video_width": f"{rule_sheet[10][1]}{rule_sheet[10][2]}",
+                    "video_height": f"{rule_sheet[11][1]}{rule_sheet[11][2]}",
+                    "like_cnt": f"{rule_sheet[12][1]}{rule_sheet[12][2]}",
+                    "duration": f"{rule_sheet[13][1]}{rule_sheet[13][2]}",
+                    "download_cnt": f"{rule_sheet[14][1]}{rule_sheet[14][2]}",
+                    "publish_time": f"{rule_sheet[15][1]}{rule_sheet[15][2]}",
+                }
+                # for k, v in rule_dict.items():
+                #     Common.logger(log_type, crawler).info(f"{k}:{v}")
+                return rule_dict
         except Exception as e:
             Common.logger(log_type, crawler).error(f"get_rule:{e}\n")
 
@@ -357,47 +352,45 @@ class KuaiShouFollow:
     @classmethod
     def get_videoList(cls, log_type, crawler, strategy, our_uid, out_uid, oss_endpoint, env, machine, pcursor=""):
         download_cnt_1, download_cnt_2 = 0, 0
-
         rule_dict_1 = cls.get_rule(log_type, crawler, 1)
         rule_dict_2 = cls.get_rule(log_type, crawler, 2)
         if rule_dict_1 is None or rule_dict_2 is None:
-            Common.logger(log_type, crawler).warning(f"rule_dict is None, 10秒后重试")
+            Common.logger(log_type, crawler).warning(f"rule_dict is None")
+            return
+        if download_cnt_1 >= int(
+                rule_dict_1['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">", "")[
+                    -1]) and download_cnt_2 >= int(
+            rule_dict_2['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">", "")[-1]):
+            Common.logger(log_type, crawler).info(
+                f"规则1已下载{download_cnt_1}条视频,规则2已下载{download_cnt_2}条视频\n")
             return
-        try:
-            if download_cnt_1 >= int(
-                    rule_dict_1['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">", "")[
-                        -1]) and download_cnt_2 >= int(
-                rule_dict_2['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">", "")[-1]):
-                Common.logger(log_type, crawler).info(
-                    f"规则1已下载{download_cnt_1}条视频,规则2已下载{download_cnt_2}条视频\n")
-                return
-
-            url = "https://www.kuaishou.com/graphql"
 
-            payload = json.dumps({
-                "operationName": "visionProfilePhotoList",
-                "variables": {
-                    "userId": out_uid,
-                    "pcursor": "",
-                    "page": "profile"
-                },
-                "query": "fragment photoContent on PhotoEntity {\n  id\n  duration\n  caption\n  originCaption\n  likeCount\n  viewCount\n  realLikeCount\n  coverUrl\n  photoUrl\n  photoH265Url\n  manifest\n  manifestH265\n  videoResource\n  coverUrls {\n    url\n    __typename\n  }\n  timestamp\n  expTag\n  animatedCoverUrl\n  distance\n  videoRatio\n  liked\n  stereoType\n  profileUserTopPhoto\n  musicBlocked\n  __typename\n}\n\nfragment feedContent on Feed {\n  type\n  author {\n    id\n    name\n    headerUrl\n    following\n    headerUrls {\n      url\n      __typename\n    }\n    __typename\n  }\n  photo {\n    ...photoContent\n    __typename\n  }\n  canAddComment\n  llsid\n  status\n  currentPcursor\n  tags {\n    type\n    name\n    __typename\n  }\n  __typename\n}\n\nquery visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {\n  visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {\n    result\n    llsid\n    webPageArea\n    feeds {\n      ...feedContent\n      __typename\n    }\n    hostName\n    pcursor\n    __typename\n  }\n}\n"
-            })
-            headers = {
-                'User-Agent':  get_random_user_agent('pc'),
-                'Accept': '*/*',
-                'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
-                'Accept-Encoding': 'gzip, deflate, br',
-                'Referer': 'https://www.kuaishou.com/profile/{}'.format(out_uid),
-                'content-type': 'application/json',
-                'Origin': 'https://www.kuaishou.com',
-                'Connection': 'keep-alive',
-                'Cookie': 'kpf=PC_WEB; clientid=3; did=web_1e446c59887cc91ea3d1bd3452b7179d; kpn=KUAISHOU_VISION',
-                'Sec-Fetch-Dest': 'empty',
-                'Sec-Fetch-Mode': 'cors',
-                'Sec-Fetch-Site': 'same-origin'
-            }
+        url = "https://www.kuaishou.com/graphql"
+        payload = json.dumps({
+            "operationName": "visionProfilePhotoList",
+            "variables": {
+                "userId": out_uid,
+                "pcursor": "",
+                "page": "profile"
+            },
+            "query": "fragment photoContent on PhotoEntity {\n  id\n  duration\n  caption\n  originCaption\n  likeCount\n  viewCount\n  realLikeCount\n  coverUrl\n  photoUrl\n  photoH265Url\n  manifest\n  manifestH265\n  videoResource\n  coverUrls {\n    url\n    __typename\n  }\n  timestamp\n  expTag\n  animatedCoverUrl\n  distance\n  videoRatio\n  liked\n  stereoType\n  profileUserTopPhoto\n  musicBlocked\n  __typename\n}\n\nfragment feedContent on Feed {\n  type\n  author {\n    id\n    name\n    headerUrl\n    following\n    headerUrls {\n      url\n      __typename\n    }\n    __typename\n  }\n  photo {\n    ...photoContent\n    __typename\n  }\n  canAddComment\n  llsid\n  status\n  currentPcursor\n  tags {\n    type\n    name\n    __typename\n  }\n  __typename\n}\n\nquery visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {\n  visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {\n    result\n    llsid\n    webPageArea\n    feeds {\n      ...feedContent\n      __typename\n    }\n    hostName\n    pcursor\n    __typename\n  }\n}\n"
+        })
+        headers = {
+            'User-Agent':  get_random_user_agent('pc'),
+            'Accept': '*/*',
+            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
+            'Accept-Encoding': 'gzip, deflate, br',
+            'Referer': 'https://www.kuaishou.com/profile/{}'.format(out_uid),
+            'content-type': 'application/json',
+            'Origin': 'https://www.kuaishou.com',
+            'Connection': 'keep-alive',
+            'Cookie': 'kpf=PC_WEB; clientid=3; did=web_1e446c59887cc91ea3d1bd3452b7179d; kpn=KUAISHOU_VISION',
+            'Sec-Fetch-Dest': 'empty',
+            'Sec-Fetch-Mode': 'cors',
+            'Sec-Fetch-Site': 'same-origin'
+        }
 
+        try:
             urllib3.disable_warnings()
             s = requests.session()
             # max_retries=3 重试3次
@@ -406,213 +399,214 @@ class KuaiShouFollow:
             response = s.post(url=url, headers=headers, data=payload, proxies=Common.tunnel_proxies(), verify=False,
                               timeout=10)
             response.close()
-            # Common.logger(log_type, crawler).info(f"get_videoList:{response.text}\n")
-            if response.status_code != 200:
-                Common.logger(log_type, crawler).warning(f"get_videoList_response:{response.text}\n")
-                return
-            elif 'data' not in response.json():
-                Common.logger(log_type, crawler).warning(f"get_videoList_response:{response.json()}\n")
-                return
-            elif 'visionProfilePhotoList' not in response.json()['data']:
-                Common.logger(log_type, crawler).warning(f"get_videoList_response:{response.json()['data']}\n")
-                return
-            elif 'feeds' not in response.json()['data']['visionProfilePhotoList']:
-                Common.logger(log_type, crawler).warning(
-                    f"get_videoList_response:{response.json()['data']['visionProfilePhotoList']}\n")
-                return
-            elif len(response.json()['data']['visionProfilePhotoList']['feeds']) == 0:
-                Common.logger(log_type, crawler).info("没有更多视频啦 ~\n")
-                return
-            else:
-                feeds = response.json()['data']['visionProfilePhotoList']['feeds']
-                pcursor = response.json()['data']['visionProfilePhotoList']['pcursor']
-                # Common.logger(log_type, crawler).info(f"feeds0: {feeds}\n")
-                for i in range(len(feeds)):
-                    if 'photo' not in feeds[i]:
-                        Common.logger(log_type, crawler).warning(f"get_videoList:{feeds[i]}\n")
-                        break
-
-                    # video_title
-                    if 'caption' not in feeds[i]['photo']:
-                        video_title = cls.random_title(log_type, crawler)
-                    elif feeds[i]['photo']['caption'].strip() == "":
-                        video_title = cls.random_title(log_type, crawler)
-                    else:
-                        video_title = cls.video_title(log_type, crawler, feeds[i]['photo']['caption'])
-
-                    if 'videoResource' not in feeds[i]['photo'] \
-                            and 'manifest' not in feeds[i]['photo'] \
-                            and 'manifestH265' not in feeds[i]['photo']:
-                        Common.logger(log_type, crawler).warning(f"get_videoList:{feeds[i]['photo']}\n")
-                        break
-                    videoResource = feeds[i]['photo']['videoResource']
-
-                    if 'h264' not in videoResource and 'hevc' not in videoResource:
-                        Common.logger(log_type, crawler).warning(f"get_videoList:{videoResource}\n")
-                        break
-
-                    # video_id
-                    if 'h264' in videoResource and 'videoId' in videoResource['h264']:
-                        video_id = videoResource['h264']['videoId']
-                    elif 'hevc' in videoResource and 'videoId' in videoResource['hevc']:
-                        video_id = videoResource['hevc']['videoId']
-                    else:
-                        video_id = ""
+        except Exception as e:
+            Common.logger(log_type, crawler).error(f"get_videoList:{e}\n")
+            return
+        # Common.logger(log_type, crawler).info(f"get_videoList:{response.text}\n")
+        if response.status_code != 200:
+            Common.logger(log_type, crawler).warning(f"get_videoList_response:{response.text}\n")
+            return
+        elif 'data' not in response.json():
+            Common.logger(log_type, crawler).warning(f"get_videoList_response:{response.json()}\n")
+            return
+        elif 'visionProfilePhotoList' not in response.json()['data']:
+            Common.logger(log_type, crawler).warning(f"get_videoList_response:{response.json()['data']}\n")
+            return
+        elif 'feeds' not in response.json()['data']['visionProfilePhotoList']:
+            Common.logger(log_type, crawler).warning(
+                f"get_videoList_response:{response.json()['data']['visionProfilePhotoList']}\n")
+            return
+        elif len(response.json()['data']['visionProfilePhotoList']['feeds']) == 0:
+            Common.logger(log_type, crawler).info("没有更多视频啦 ~\n")
+            return
+        else:
+            feeds = response.json()['data']['visionProfilePhotoList']['feeds']
+            pcursor = response.json()['data']['visionProfilePhotoList']['pcursor']
+            # Common.logger(log_type, crawler).info(f"feeds0: {feeds}\n")
+            for i in range(len(feeds)):
+                if 'photo' not in feeds[i]:
+                    Common.logger(log_type, crawler).warning(f"get_videoList:{feeds[i]}\n")
+                    break
+
+                # video_title
+                if 'caption' not in feeds[i]['photo']:
+                    video_title = cls.random_title(log_type, crawler)
+                elif feeds[i]['photo']['caption'].strip() == "":
+                    video_title = cls.random_title(log_type, crawler)
+                else:
+                    video_title = cls.video_title(log_type, crawler, feeds[i]['photo']['caption'])
+
+                if 'videoResource' not in feeds[i]['photo'] \
+                        and 'manifest' not in feeds[i]['photo'] \
+                        and 'manifestH265' not in feeds[i]['photo']:
+                    Common.logger(log_type, crawler).warning(f"get_videoList:{feeds[i]['photo']}\n")
+                    break
+                videoResource = feeds[i]['photo']['videoResource']
+
+                if 'h264' not in videoResource and 'hevc' not in videoResource:
+                    Common.logger(log_type, crawler).warning(f"get_videoList:{videoResource}\n")
+                    break
+
+                # video_id
+                if 'h264' in videoResource and 'videoId' in videoResource['h264']:
+                    video_id = videoResource['h264']['videoId']
+                elif 'hevc' in videoResource and 'videoId' in videoResource['hevc']:
+                    video_id = videoResource['hevc']['videoId']
+                else:
+                    video_id = ""
 
-                    # play_cnt
-                    if 'viewCount' not in feeds[i]['photo']:
-                        play_cnt = 0
-                    else:
-                        play_cnt = int(feeds[i]['photo']['viewCount'])
+                # play_cnt
+                if 'viewCount' not in feeds[i]['photo']:
+                    play_cnt = 0
+                else:
+                    play_cnt = int(feeds[i]['photo']['viewCount'])
 
-                    # like_cnt
-                    if 'realLikeCount' not in feeds[i]['photo']:
-                        like_cnt = 0
-                    else:
-                        like_cnt = feeds[i]['photo']['realLikeCount']
+                # like_cnt
+                if 'realLikeCount' not in feeds[i]['photo']:
+                    like_cnt = 0
+                else:
+                    like_cnt = feeds[i]['photo']['realLikeCount']
 
-                    # publish_time
-                    if 'timestamp' not in feeds[i]['photo']:
-                        publish_time_stamp = 0
-                        publish_time_str = ''
-                        publish_time = 0
-                    else:
-                        publish_time_stamp = int(int(feeds[i]['photo']['timestamp']) / 1000)
-                        publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
-                        publish_time = int((int(time.time()) - publish_time_stamp) / (3600 * 24))
+                # publish_time
+                if 'timestamp' not in feeds[i]['photo']:
+                    publish_time_stamp = 0
+                    publish_time_str = ''
+                    publish_time = 0
+                else:
+                    publish_time_stamp = int(int(feeds[i]['photo']['timestamp']) / 1000)
+                    publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
+                    publish_time = int((int(time.time()) - publish_time_stamp) / (3600 * 24))
 
-                    # duration
-                    if 'duration' not in feeds[i]['photo']:
-                        duration = 0
-                    else:
-                        duration = int(int(feeds[i]['photo']['duration']) / 1000)
-
-                    # video_width / video_height / video_url
-                    mapping = {}
-                    for item in ['width', 'height']:
-                        try:
-                            val = str(videoResource['h264']['adaptationSet'][0]['representation'][0][item])
-                        except Exception:
-                            val = str(videoResource['hevc']['adaptationSet'][0]['representation'][0][item])
-                        except:
-                            val = ''
-                        mapping[item] = val
-                    video_width = int(mapping['width']) if mapping['width'] != '' else 0
-                    video_height = int(mapping['height']) if mapping['height'] != '' else 0
-                    # cover_url
-                    if 'coverUrl' not in feeds[i]['photo']:
-                        cover_url = ""
-                    else:
-                        cover_url = feeds[i]['photo']['coverUrl']
+                # duration
+                if 'duration' not in feeds[i]['photo']:
+                    duration = 0
+                else:
+                    duration = int(int(feeds[i]['photo']['duration']) / 1000)
 
-                    # user_name / avatar_url
+                # video_width / video_height / video_url
+                mapping = {}
+                for item in ['width', 'height']:
                     try:
-                        user_name = feeds[i]['author']['name']
-                        avatar_url = feeds[i]['author']['headerUrl']
+                        val = str(videoResource['h264']['adaptationSet'][0]['representation'][0][item])
                     except Exception:
-                        user_name = ''
-                        avatar_url = ''
-
-                    video_url = feeds[i]['photo']['photoUrl']
-                    video_dict = {'video_title': video_title,
-                                  'video_id': video_id,
-                                  'play_cnt': play_cnt,
-                                  'comment_cnt': 0,
-                                  'like_cnt': like_cnt,
-                                  'share_cnt': 0,
-                                  'video_width': video_width,
-                                  'video_height': video_height,
-                                  'duration': duration,
-                                  'publish_time': publish_time,
-                                  'publish_time_stamp': publish_time_stamp,
-                                  'publish_time_str': publish_time_str,
-                                  'user_name': user_name,
-                                  'user_id': out_uid,
-                                  'avatar_url': avatar_url,
-                                  'cover_url': cover_url,
-                                  'video_url': video_url,
-                                  'session': f"kuaishou{int(time.time())}"}
-
-                    rule_1 = cls.download_rule(video_dict, rule_dict_1)
-                    Common.logger(log_type, crawler).info(f"video_title:{video_title}")
-                    Common.logger(log_type, crawler).info(f"video_id:{video_id}\n")
-
-                    Common.logger(log_type, crawler).info(
-                        f"play_cnt:{video_dict['play_cnt']}{rule_dict_1['play_cnt']}, {eval(str(video_dict['play_cnt']) + str(rule_dict_1['play_cnt']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"like_cnt:{video_dict['like_cnt']}{rule_dict_1['like_cnt']}, {eval(str(video_dict['like_cnt']) + str(rule_dict_1['like_cnt']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"video_width:{video_dict['video_width']}{rule_dict_1['video_width']}, {eval(str(video_dict['video_width']) + str(rule_dict_1['video_width']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"video_height:{video_dict['video_height']}{rule_dict_1['video_height']}, {eval(str(video_dict['video_height']) + str(rule_dict_1['video_height']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"duration:{video_dict['duration']}{rule_dict_1['duration']}, {eval(str(video_dict['duration']) + str(rule_dict_1['duration']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"publish_time:{video_dict['publish_time']}{rule_dict_1['publish_time']}, {eval(str(video_dict['publish_time']) + str(rule_dict_1['publish_time']))}")
-                    Common.logger(log_type, crawler).info(f"rule_1:{rule_1}\n")
-
-                    rule_2 = cls.download_rule(video_dict, rule_dict_2)
-                    Common.logger(log_type, crawler).info(
-                        f"play_cnt:{video_dict['play_cnt']}{rule_dict_2['play_cnt']}, {eval(str(video_dict['play_cnt']) + str(rule_dict_2['play_cnt']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"like_cnt:{video_dict['like_cnt']}{rule_dict_2['like_cnt']}, {eval(str(video_dict['like_cnt']) + str(rule_dict_2['like_cnt']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"video_width:{video_dict['video_width']}{rule_dict_2['video_width']}, {eval(str(video_dict['video_width']) + str(rule_dict_2['video_width']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"video_height:{video_dict['video_height']}{rule_dict_2['video_height']}, {eval(str(video_dict['video_height']) + str(rule_dict_2['video_height']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"duration:{video_dict['duration']}{rule_dict_2['duration']}, {eval(str(video_dict['duration']) + str(rule_dict_2['duration']))}")
-                    Common.logger(log_type, crawler).info(
-                        f"publish_time:{video_dict['publish_time']}{rule_dict_2['publish_time']}, {eval(str(video_dict['publish_time']) + str(rule_dict_2['publish_time']))}")
-                    Common.logger(log_type, crawler).info(f"rule_2:{rule_2}\n")
-
-                    if video_title == "" or video_url == "":
-                        Common.logger(log_type, crawler).info("无效视频\n")
-                        continue
-                    elif rule_1 is True:
-                        if download_cnt_1 < int(
-                                rule_dict_1['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">",
-                                                                                                              "")[
-                                    -1]):
-                            download_finished = cls.download_publish(log_type=log_type,
-                                                                     crawler=crawler,
-                                                                     strategy=strategy,
-                                                                     video_dict=video_dict,
-                                                                     rule_dict=rule_dict_1,
-                                                                     our_uid=our_uid,
-                                                                     oss_endpoint=oss_endpoint,
-                                                                     env=env,
-                                                                     machine=machine)
-                            if download_finished is True:
-                                download_cnt_1 += 1
-                    elif rule_2 is True:
-                        if download_cnt_2 < int(
-                                rule_dict_2['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">",
-                                                                                                              "")[
-                                    -1]):
-                            download_finished = cls.download_publish(log_type=log_type,
-                                                                     crawler=crawler,
-                                                                     strategy=strategy,
-                                                                     video_dict=video_dict,
-                                                                     rule_dict=rule_dict_2,
-                                                                     our_uid=our_uid,
-                                                                     oss_endpoint=oss_endpoint,
-                                                                     env=env,
-                                                                     machine=machine)
-                            if download_finished is True:
-                                download_cnt_2 += 1
-                    else:
-                        Common.logger(log_type, crawler).info("不满足下载规则\n")
-                        # Common.logger(log_type, crawler).info(f"feeds: {feeds}\n")
+                        val = str(videoResource['hevc']['adaptationSet'][0]['representation'][0][item])
+                    except:
+                        val = ''
+                    mapping[item] = val
+                video_width = int(mapping['width']) if mapping['width'] != '' else 0
+                video_height = int(mapping['height']) if mapping['height'] != '' else 0
+                # cover_url
+                if 'coverUrl' not in feeds[i]['photo']:
+                    cover_url = ""
+                else:
+                    cover_url = feeds[i]['photo']['coverUrl']
 
-                if pcursor == "no_more":
-                    Common.logger(log_type, crawler).info(f"作者,{out_uid},已经到底了,没有更多内容了\n")
-                    return
+                # user_name / avatar_url
+                try:
+                    user_name = feeds[i]['author']['name']
+                    avatar_url = feeds[i]['author']['headerUrl']
+                except Exception:
+                    user_name = ''
+                    avatar_url = ''
+
+                video_url = feeds[i]['photo']['photoUrl']
+                video_dict = {'video_title': video_title,
+                              'video_id': video_id,
+                              'play_cnt': play_cnt,
+                              'comment_cnt': 0,
+                              'like_cnt': like_cnt,
+                              'share_cnt': 0,
+                              'video_width': video_width,
+                              'video_height': video_height,
+                              'duration': duration,
+                              'publish_time': publish_time,
+                              'publish_time_stamp': publish_time_stamp,
+                              'publish_time_str': publish_time_str,
+                              'user_name': user_name,
+                              'user_id': out_uid,
+                              'avatar_url': avatar_url,
+                              'cover_url': cover_url,
+                              'video_url': video_url,
+                              'session': f"kuaishou{int(time.time())}"}
+
+                rule_1 = cls.download_rule(video_dict, rule_dict_1)
+                Common.logger(log_type, crawler).info(f"video_title:{video_title}")
+                Common.logger(log_type, crawler).info(f"video_id:{video_id}\n")
+
+                Common.logger(log_type, crawler).info(
+                    f"play_cnt:{video_dict['play_cnt']}{rule_dict_1['play_cnt']}, {eval(str(video_dict['play_cnt']) + str(rule_dict_1['play_cnt']))}")
+                Common.logger(log_type, crawler).info(
+                    f"like_cnt:{video_dict['like_cnt']}{rule_dict_1['like_cnt']}, {eval(str(video_dict['like_cnt']) + str(rule_dict_1['like_cnt']))}")
+                Common.logger(log_type, crawler).info(
+                    f"video_width:{video_dict['video_width']}{rule_dict_1['video_width']}, {eval(str(video_dict['video_width']) + str(rule_dict_1['video_width']))}")
+                Common.logger(log_type, crawler).info(
+                    f"video_height:{video_dict['video_height']}{rule_dict_1['video_height']}, {eval(str(video_dict['video_height']) + str(rule_dict_1['video_height']))}")
+                Common.logger(log_type, crawler).info(
+                    f"duration:{video_dict['duration']}{rule_dict_1['duration']}, {eval(str(video_dict['duration']) + str(rule_dict_1['duration']))}")
+                Common.logger(log_type, crawler).info(
+                    f"publish_time:{video_dict['publish_time']}{rule_dict_1['publish_time']}, {eval(str(video_dict['publish_time']) + str(rule_dict_1['publish_time']))}")
+                Common.logger(log_type, crawler).info(f"rule_1:{rule_1}\n")
+
+                rule_2 = cls.download_rule(video_dict, rule_dict_2)
+                Common.logger(log_type, crawler).info(
+                    f"play_cnt:{video_dict['play_cnt']}{rule_dict_2['play_cnt']}, {eval(str(video_dict['play_cnt']) + str(rule_dict_2['play_cnt']))}")
+                Common.logger(log_type, crawler).info(
+                    f"like_cnt:{video_dict['like_cnt']}{rule_dict_2['like_cnt']}, {eval(str(video_dict['like_cnt']) + str(rule_dict_2['like_cnt']))}")
+                Common.logger(log_type, crawler).info(
+                    f"video_width:{video_dict['video_width']}{rule_dict_2['video_width']}, {eval(str(video_dict['video_width']) + str(rule_dict_2['video_width']))}")
+                Common.logger(log_type, crawler).info(
+                    f"video_height:{video_dict['video_height']}{rule_dict_2['video_height']}, {eval(str(video_dict['video_height']) + str(rule_dict_2['video_height']))}")
+                Common.logger(log_type, crawler).info(
+                    f"duration:{video_dict['duration']}{rule_dict_2['duration']}, {eval(str(video_dict['duration']) + str(rule_dict_2['duration']))}")
+                Common.logger(log_type, crawler).info(
+                    f"publish_time:{video_dict['publish_time']}{rule_dict_2['publish_time']}, {eval(str(video_dict['publish_time']) + str(rule_dict_2['publish_time']))}")
+                Common.logger(log_type, crawler).info(f"rule_2:{rule_2}\n")
+
+                if video_title == "" or video_url == "":
+                    Common.logger(log_type, crawler).info("无效视频\n")
+                    continue
+                elif rule_1 is True:
+                    if download_cnt_1 < int(
+                            rule_dict_1['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">",
+                                                                                                          "")[
+                                -1]):
+                        download_finished = cls.download_publish(log_type=log_type,
+                                                                 crawler=crawler,
+                                                                 strategy=strategy,
+                                                                 video_dict=video_dict,
+                                                                 rule_dict=rule_dict_1,
+                                                                 our_uid=our_uid,
+                                                                 oss_endpoint=oss_endpoint,
+                                                                 env=env,
+                                                                 machine=machine)
+                        if download_finished is True:
+                            download_cnt_1 += 1
+                elif rule_2 is True:
+                    if download_cnt_2 < int(
+                            rule_dict_2['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">",
+                                                                                                          "")[
+                                -1]):
+                        download_finished = cls.download_publish(log_type=log_type,
+                                                                 crawler=crawler,
+                                                                 strategy=strategy,
+                                                                 video_dict=video_dict,
+                                                                 rule_dict=rule_dict_2,
+                                                                 our_uid=our_uid,
+                                                                 oss_endpoint=oss_endpoint,
+                                                                 env=env,
+                                                                 machine=machine)
+                        if download_finished is True:
+                            download_cnt_2 += 1
+                else:
+                    Common.logger(log_type, crawler).info("不满足下载规则\n")
+                    # Common.logger(log_type, crawler).info(f"feeds: {feeds}\n")
+
+            if pcursor == "no_more":
+                Common.logger(log_type, crawler).info(f"作者,{out_uid},已经到底了,没有更多内容了\n")
+                return
             cls.get_videoList(log_type, crawler, strategy, our_uid, out_uid, oss_endpoint, env, machine,
-                              pcursor=pcursor)
+                          pcursor=pcursor)
             time.sleep(random.randint(3, 5))
-        except Exception as e:
-            Common.logger(log_type, crawler).error(f"get_videoList:{e}\n")
 
     @classmethod
     def repeat_video(cls, log_type, crawler, video_id, video_title, publish_time, env, machine):

+ 16 - 0
main/process.sh

@@ -127,6 +127,22 @@ else
   echo "$(date "+%Y-%m-%d %H:%M:%S") 快手定向爬虫策略 进程状态正常" >> ${log_path}
 fi
 
+#
+## 抖音推荐爬虫策略
+#echo "$(date "+%Y-%m-%d %H:%M:%S") 正在监测 抖音推荐爬虫策略 进程状态" >> ${log_path}
+#ps -ef | grep "run_douyin_recommend.py" | grep -v "grep"
+#if [ "$?" -eq 1 ];then
+#  echo "$(date "+%Y-%m-%d_%H:%M:%S") 异常停止,正在重启!" >> ${log_path}
+#  if [ ${env} = "dev" ];then
+#    cd ${piaoquan_crawler_dir} && sh main/scheduling_main.sh ./kuaishou/kuaishou_main/run_kuaishou_follow.py --log_type="follow" --crawler="kuaishou" --env="dev" xiaoniangao/nohup-play.log
+#  else
+#    cd ${piaoquan_crawler_dir} && /usr/bin/sh ./main/main.sh ./douyin/douyin_main/run_douyin_recommend.py --log_type="recommend" --crawler="douyin" --strategy="抖音推荐爬虫策略" --oss_endpoint="inner" --env="prod" --machine="aliyun" douyin/recommend.log
+#  fi
+#  echo "$(date "+%Y-%m-%d %H:%M:%S") 重启完成!" >> ${log_path}
+#else
+#  echo "$(date "+%Y-%m-%d %H:%M:%S") 抖音推荐爬虫策略 进程状态正常" >> ${log_path}
+#fi
+
 # 西瓜定向爬虫策略
 echo "$(date "+%Y-%m-%d %H:%M:%S") 正在监测 西瓜定向爬虫策略 进程状态" >> ${log_path}
 ps -ef | grep "run_xigua_follow.py" | grep -v "grep"