소스 검색

Merge branch 'master' into lxr_etl_20230620

ehlxr 1 년 전
부모
커밋
c1f08e974e

+ 1 - 1
.gitignore

@@ -4,7 +4,6 @@ __pycache__/
 *.py[cod]
 *$py.class
 *.DS_Store
-
 # C extensions
 *.so
 
@@ -26,6 +25,7 @@ var/
 *.egg-info/
 .installed.cfg
 *.egg
+.DS_Store
 
 # PyInstaller
 #  Usually these files are written by a python script from a template

+ 3 - 4
common/common.py

@@ -44,8 +44,7 @@ class Common:
         # 日志文件名
         # log_name = time.strftime("%Y-%m-%d", time.localtime(time.time())) + f'-{crawler}-{log_type}.log'
         # log_name = datetime.datetime.now().strftime('%Y-%m-%d') + f'-{crawler}-{log_type}.log'
-        log_name = datetime.datetime.now().strftime('%Y-%m-%d') + '-' + crawler + '-' + log_type + '.log'
-        # log_name = str(date.today()) + f"-{crawler}-{log_type}.log"
+        log_name = f"{date.today()}-{crawler}-{log_type}.log"
 
         # 日志不打印到控制台
         logger.remove(handler_id=None)
@@ -55,7 +54,7 @@ class Common:
         # rotation="1 week",每周创建一个文件
         # retention="10 days",每隔10天之后就会清理旧的日志
         # 初始化日志
-        logger.add(f"{log_dir}{log_name}", level="INFO", rotation='00:00')
+        logger.add(f"{log_dir}{log_name}", level="INFO", rotation=datetime.time(hour=0, minute=0), retention="10 days", enqueue=True)
 
         return logger
 
@@ -478,5 +477,5 @@ class Common:
 
 
 if __name__ == "__main__":
-
+    print(datetime.time(hour=0, minute=0))
     pass

+ 14 - 13
common/public.py

@@ -218,19 +218,20 @@ def get_word_score(log_type, crawler, score_sheet, word):
 
 def get_title_score(log_type, crawler, stop_sheet, score_sheet, title):
     # 获取停用词列表
-    while True:
-        stop_word_list = []
-        stop_word_sheet = Feishu.get_values_batch(log_type, crawler, stop_sheet)
-        if stop_word_sheet is None:
-            time.sleep(1)
-            continue
-        for x in stop_word_sheet:
-            for y in x:
-                if y is None:
-                    pass
-                else:
-                    stop_word_list.append(y)
-        break
+    # while True:
+    stop_word_list = []
+    stop_word_sheet = Feishu.get_values_batch(log_type, crawler, stop_sheet)
+    if stop_word_sheet is None:
+        return 0
+        # time.sleep(1)
+        # continue
+    for x in stop_word_sheet:
+        for y in x:
+            if y is None:
+                pass
+            else:
+                stop_word_list.append(y)
+        # break
 
     # 文本分词
     cut_word_list = []

+ 3 - 3
common/publish.py

@@ -172,9 +172,9 @@ class Publish:
         :param our_uid: 上传到指定站内 UID
         :return: uid
         """
-        # if env == 'dev':
-        #     uids_dev = [6267140, 6267141]
-        #     return random.choice(uids_dev)
+        if env == 'dev':
+            uids_dev = [6267140, 6267141]
+            return random.choice(uids_dev)
 
         if crawler == 'kanyikan' and env == 'prod' and strategy == '推荐抓取策略':
             uids_prod_kanyikan_recommend = [20631208, 20631209, 20631210, 20631211, 20631212,

+ 2 - 1
ganggangdouchuan/ganggangdouchuan_recommend/ganggangdouchuan_recommend.py

@@ -134,7 +134,7 @@ class GanggangdouchuanRecommend:
     def check_to_applet(cls, log_type, crawler, driver: WebDriver):
         while True:
             webview = driver.contexts
-            # Common.logger(log_type, crawler).info(f"webviews:{webview}")
+            Common.logger(log_type, crawler).info(f"webviews:{webview}")
             driver.switch_to.context(webview[1])
             windowHandles = driver.window_handles
             for handle in windowHandles:
@@ -227,6 +227,7 @@ class GanggangdouchuanRecommend:
                         Common.logger(log_type, crawler).info('视频已下载\n')
                     else:
                         video_url = cls.get_video_url(log_type, crawler, driver, video_element)
+                        Common.logger(log_type, crawler).info(f'video_url:{video_url}')
                         if video_url is None:
                             Common.logger(log_type, crawler).info("未获取到视频播放地址\n")
                             driver.press_keycode(AndroidKey.BACK)

+ 0 - 3
kanyikan/chlsfiles/__init__.txt

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

+ 1 - 2
kanyikan/kanyikan_main/run_kyk_recommend.py

@@ -10,7 +10,7 @@ sys.path.append(os.getcwd())
 from common.common import Common
 from common.public import get_consumer, ack_message, task_fun_mq
 from common.scheduling_db import MysqlHelper
-from kanyikan.kanyikan_recommend.kanyikan_recommend import KanyikanRecommend
+from kanyikan.kanyikan_recommend.kanyikan_recommend0627 import KanyikanRecommend
 
 
 def main(log_type, crawler, topic_name, group_id, env):
@@ -78,7 +78,6 @@ 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_charles_files(log_type, crawler)
                 Common.logger(log_type, crawler).info('抓取一轮结束\n')
                 Common.logging(log_type, crawler, env, '抓取一轮结束\n')

+ 21 - 0
kanyikan/kanyikan_main/run_kyk_recommend_dev.py

@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2023/6/27
+import os
+import sys
+sys.path.append(os.getcwd())
+from common.common import Common
+from kanyikan.kanyikan_recommend.kanyikan_recommend0627 import KanyikanRecommend
+
+
+def kanyikan_main(log_type, crawler, env):
+    Common.logger(log_type, crawler).info(f'开始抓取:看一看推荐\n')
+    KanyikanRecommend.get_videoList(log_type=log_type,
+                                    crawler=crawler,
+                                    rule_dict={},
+                                    our_uid=6267140,
+                                    env=env)
+
+
+if __name__ == "__main__":
+    kanyikan_main(log_type="recommend", crawler="kanyikan", env="dev")

+ 275 - 0
kanyikan/kanyikan_recommend/kanyikan_recommend0627.py

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

+ 2 - 2
main/process_mq.sh

@@ -55,7 +55,7 @@ fi
 
 
 # 删除日志
-echo "$(date "+%Y-%m-%d %H:%M:%S") 开始清理 5 天前的日志文件" >> ${log_path}
-find ${piaoquan_crawler_dir}main/main_logs/ -mtime +5 -name "*.log" -exec rm -rf {} \;
+echo "$(date "+%Y-%m-%d %H:%M:%S") 开始清理 10 天前的日志文件" >> ${log_path}
+find ${piaoquan_crawler_dir}main/main_logs/ -mtime +10 -name "*.log" -exec rm -rf {} \;
 echo "$(date "+%Y-%m-%d %H:%M:%S") 日志文件清理完毕" >> ${log_path}
 exit 0

+ 110 - 110
shipinhao/shipinhao_search/shipinhao_search.py

@@ -187,8 +187,8 @@ class ShipinhaoSearch:
             # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
             "showChromedriverLog": True,
             # "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
-            # "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
-            "chromeOptions": {"androidProcess": "com.tencent.mm:toolsmp"},
+            "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
+            # "chromeOptions": {"androidProcess": "com.tencent.mm:toolsmp"},
             # "chromeOptions": {"androidProcess": "com.tencent.mm"},
             'enableWebviewDetailsCollection': True,
             'setWebContentsDebuggingEnabled': True,
@@ -391,7 +391,7 @@ class ShipinhaoSearch:
         driver.switch_to.context('NATIVE_APP')
 
         # 点赞
-        like_id = driver.find_element(By.ID, 'com.tencent.mm:id/k04')
+        like_id = driver.find_element(By.ID, 'com.tencent.mm:id/k04')  # 微信版本 8.0.30
         like_cnt = like_id.get_attribute('name')
         if like_cnt == "" or like_cnt == "喜欢" or like_cnt == "火" or cls.is_contain_chinese(like_cnt) is True:
             like_cnt = 0
@@ -549,16 +549,16 @@ class ShipinhaoSearch:
         driver.implicitly_wait(10)
         Common.logger(log_type, crawler).info("点击搜索框")
         Common.logging(log_type, crawler, env, "点击搜索框")
-        # driver.find_element(By.ID, 'com.tencent.mm:id/j5t').click()  # 微信8.0.30版本
-        driver.find_element(By.ID, 'com.tencent.mm:id/he6').click()  # 微信8.0.16版本
+        driver.find_element(By.ID, 'com.tencent.mm:id/j5t').click()  # 微信8.0.30版本
+        # driver.find_element(By.ID, 'com.tencent.mm:id/he6').click()  # 微信8.0.16版本
         time.sleep(0.5)
-        # driver.find_element(By.ID, 'com.tencent.mm:id/cd7').clear().send_keys(word)  # 微信8.0.30版本
-        driver.find_element(By.ID, 'com.tencent.mm:id/bxz').clear().send_keys(word)  # 微信8.0.16版本
+        driver.find_element(By.ID, 'com.tencent.mm:id/cd7').clear().send_keys(word)  # 微信8.0.30版本
+        # driver.find_element(By.ID, 'com.tencent.mm:id/bxz').clear().send_keys(word)  # 微信8.0.16版本
         driver.press_keycode(AndroidKey.ENTER)
         Common.logger(log_type, crawler).info("进入搜索词页面")
         Common.logging(log_type, crawler, env, "进入搜索词页面")
-        # driver.find_elements(By.ID, 'com.tencent.mm:id/br8')[0].click()  # 微信8.0.30版本
-        driver.find_elements(By.ID, 'com.tencent.mm:id/jkg')[0].click()  # 微信8.0.16版本
+        driver.find_elements(By.ID, 'com.tencent.mm:id/br8')[0].click()  # 微信8.0.30版本
+        # driver.find_elements(By.ID, 'com.tencent.mm:id/jkg')[0].click()  # 微信8.0.16版本
         time.sleep(5)
 
         # 切换到微信搜索结果页 webview
@@ -598,93 +598,93 @@ class ShipinhaoSearch:
                 return
 
             for i, video_element in enumerate(video_element_temp):
-                # try:
-                Common.logger(log_type, crawler).info(f"download_cnt:{cls.download_cnt}")
-                Common.logging(log_type, crawler, env, f"download_cnt:{cls.download_cnt}")
-                if cls.download_cnt >= cls.videos_cnt(log_type, crawler):
-                    Common.logger(log_type, crawler).info(f'搜索词:"{word}",已抓取视频数:{cls.download_cnt}')
-                    Common.logging(log_type, crawler, env, f'搜索词:"{word}",已抓取视频数:{cls.download_cnt}')
-                    cls.download_cnt = 0
-                    return
-
-                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(driver, '//*[@class="rich-media active__absolute"]')
-
-                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)
-                if len(video_element.find_elements(By.XPATH, "//*[@text='没有更多的搜索结果']")) != 0:
-                    Common.logger(log_type, crawler).info("没有更多的搜索结果\n")
-                    Common.logging(log_type, crawler, env, "没有更多的搜索结果\n")
-                    return
-                video_title = video_element.find_elements(By.XPATH, '//div[@class="rich-media__title ellipsis_2"]/span')[index + i].text[:40]
-                video_url = video_element.find_elements(By.XPATH, '//div[@class="video-player"]')[index+i].get_attribute('src')
-                cover_url = video_element.find_elements(By.XPATH, '//div[@class="video-player__bd"]')[index+i].get_attribute('style')
-                cover_url = cover_url.split('url("')[-1].split('")')[0]
-                duration = video_element.find_elements(By.XPATH, '//div[@class="video-player-mask__text"]')[index+i].text
-                duration = int(duration.split(':')[0]) * 60 + int(duration.split(':')[-1])
-                user_name = video_element.find_elements(By.XPATH, '//div[@class="rich-media__source__title"]')[index+i].text
-                avatar_url = video_element.find_elements(By.XPATH, '//div[@class="ui-image-image ui-image rich-media__source__thumb"]')[index+i].get_attribute('style')
-                avatar_url = avatar_url.split('url("')[-1].split('")')[0]
-                out_video_id = md5(video_title.encode('utf8')).hexdigest()
-                out_user_id = md5(user_name.encode('utf8')).hexdigest()
-
-                video_dict = {
-                    "video_title": video_title,
-                    "video_id": out_video_id,
-                    "play_cnt": 0,
-                    "duration": duration,
-                    "user_name": user_name,
-                    "user_id": out_user_id,
-                    "avatar_url": avatar_url,
-                    "cover_url": cover_url,
-                    "video_url": video_url,
-                    "session": f"shipinhao-search-{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}")
-                if video_title is None or video_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')
-                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')
-                else:
-                    video_element.click()
+                try:
+                    Common.logger(log_type, crawler).info(f"download_cnt:{cls.download_cnt}")
+                    Common.logging(log_type, crawler, env, f"download_cnt:{cls.download_cnt}")
+                    if cls.download_cnt >= cls.videos_cnt(log_type, crawler):
+                        Common.logger(log_type, crawler).info(f'搜索词:"{word}",已抓取视频数:{cls.download_cnt}')
+                        Common.logging(log_type, crawler, env, f'搜索词:"{word}",已抓取视频数:{cls.download_cnt}')
+                        cls.download_cnt = 0
+                        return
+
+                    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(driver, '//*[@class="rich-media active__absolute"]')
+
+                    Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
+                    Common.logging(log_type, crawler, env, f'拖动"视频"列表第{cls.i}个至屏幕中间')
                     time.sleep(3)
-                    video_info_dict = cls.get_video_info(driver)
-                    video_dict["like_cnt"] = video_info_dict["like_cnt"]
-                    video_dict["share_cnt"] = video_info_dict["share_cnt"]
-                    video_dict["favorite_cnt"] = video_info_dict["favorite_cnt"]
-                    video_dict["comment_cnt"] = video_info_dict["comment_cnt"]
-                    video_dict["publish_time_str"] = video_info_dict["publish_time_str"]
-                    video_dict["publish_time_stamp"] = video_info_dict["publish_time_stamp"]
-                    Common.logger(log_type, crawler).info(f'publish_time:{video_dict["publish_time_str"]}')
-                    Common.logging(log_type, crawler, env, f'publish_time:{video_dict["publish_time_str"]}')
-                    if cls.download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict) is False:
-                        Common.logger(log_type, crawler).info("不满足抓取规则\n")
-                        Common.logging(log_type, crawler, env, "不满足抓取规则\n")
+                    driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})",
+                                          video_element)
+                    if len(video_element.find_elements(By.XPATH, "//*[@text='没有更多的搜索结果']")) != 0:
+                        Common.logger(log_type, crawler).info("没有更多的搜索结果\n")
+                        Common.logging(log_type, crawler, env, "没有更多的搜索结果\n")
+                        return
+                    video_title = video_element.find_elements(By.XPATH, '//div[@class="rich-media__title ellipsis_2"]/span')[index + i].text[:40]
+                    video_url = video_element.find_elements(By.XPATH, '//div[@class="video-player"]')[index+i].get_attribute('src')
+                    cover_url = video_element.find_elements(By.XPATH, '//div[@class="video-player__bd"]')[index+i].get_attribute('style')
+                    cover_url = cover_url.split('url("')[-1].split('")')[0]
+                    duration = video_element.find_elements(By.XPATH, '//div[@class="video-player-mask__text"]')[index+i].text
+                    duration = int(duration.split(':')[0]) * 60 + int(duration.split(':')[-1])
+                    user_name = video_element.find_elements(By.XPATH, '//div[@class="rich-media__source__title"]')[index+i].text
+                    avatar_url = video_element.find_elements(By.XPATH, '//div[@class="ui-image-image ui-image rich-media__source__thumb"]')[index+i].get_attribute('style')
+                    avatar_url = avatar_url.split('url("')[-1].split('")')[0]
+                    out_video_id = md5(video_title.encode('utf8')).hexdigest()
+                    out_user_id = md5(user_name.encode('utf8')).hexdigest()
+
+                    video_dict = {
+                        "video_title": video_title,
+                        "video_id": out_video_id,
+                        "play_cnt": 0,
+                        "duration": duration,
+                        "user_name": user_name,
+                        "user_id": out_user_id,
+                        "avatar_url": avatar_url,
+                        "cover_url": cover_url,
+                        "video_url": video_url,
+                        "session": f"shipinhao-search-{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}")
+                    if video_title is None or video_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')
+                    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')
                     else:
-                        cls.download_publish(log_type=log_type,
-                                             crawler=crawler,
-                                             word=word,
-                                             video_dict=video_dict,
-                                             our_uid=our_uid,
-                                             env=env)
-                # except Exception as e:
-                #     Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
-                #     Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
+                        video_element.click()
+                        time.sleep(3)
+                        video_info_dict = cls.get_video_info(driver)
+                        video_dict["like_cnt"] = video_info_dict["like_cnt"]
+                        video_dict["share_cnt"] = video_info_dict["share_cnt"]
+                        video_dict["favorite_cnt"] = video_info_dict["favorite_cnt"]
+                        video_dict["comment_cnt"] = video_info_dict["comment_cnt"]
+                        video_dict["publish_time_str"] = video_info_dict["publish_time_str"]
+                        video_dict["publish_time_stamp"] = video_info_dict["publish_time_stamp"]
+                        Common.logger(log_type, crawler).info(f'publish_time:{video_dict["publish_time_str"]}')
+                        Common.logging(log_type, crawler, env, f'publish_time:{video_dict["publish_time_str"]}')
+                        if cls.download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict) is False:
+                            Common.logger(log_type, crawler).info("不满足抓取规则\n")
+                            Common.logging(log_type, crawler, env, "不满足抓取规则\n")
+                        else:
+                            cls.download_publish(log_type=log_type,
+                                                 crawler=crawler,
+                                                 word=word,
+                                                 video_dict=video_dict,
+                                                 our_uid=our_uid,
+                                                 env=env)
+                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('已抓取完一组视频,休眠1秒\n')
             Common.logging(log_type, crawler, env, '已抓取完一组视频,休眠1秒\n')
@@ -695,22 +695,22 @@ class ShipinhaoSearch:
     def get_search_videos(cls, log_type, crawler, env):
         user_list = cls.get_users(log_type, crawler, "wNgi6Z", env)
         for user in user_list:
-            # try:
-            cls.i = 0
-            cls.download_cnt = 0
-            search_word = user["search_word"]
-            our_uid = user["our_uid"]
-            Common.logger(log_type, crawler).info(f"开始抓取:{search_word}")
-            Common.logging(log_type, crawler, env, f"开始抓取:{search_word}")
-
-            cls.start_wechat(log_type=log_type,
-                             crawler=crawler,
-                             word=search_word,
-                             our_uid=our_uid,
-                             env=env)
-            # except Exception as e:
-            #     Common.logger(log_type, crawler).error(f"抓取{user['search_word']}时异常:{e}\n")
-            #     Common.logging(log_type, crawler, env, f"抓取{user['search_word']}时异常:{e}\n")
+            try:
+                cls.i = 0
+                cls.download_cnt = 0
+                search_word = user["search_word"]
+                our_uid = user["our_uid"]
+                Common.logger(log_type, crawler).info(f"开始抓取:{search_word}")
+                Common.logging(log_type, crawler, env, f"开始抓取:{search_word}")
+
+                cls.start_wechat(log_type=log_type,
+                                 crawler=crawler,
+                                 word=search_word,
+                                 our_uid=our_uid,
+                                 env=env)
+            except Exception as e:
+                Common.logger(log_type, crawler).error(f"抓取{user['search_word']}时异常:{e}\n")
+                Common.logging(log_type, crawler, env, f"抓取{user['search_word']}时异常:{e}\n")
 
 
 if __name__ == '__main__':

+ 1 - 0
xigua/xigua_search/xigua_search_scheduling.py

@@ -611,6 +611,7 @@ class XiguasearchScheduling:
                         Common.logging(log_type, crawler, env, '到底啦~\n')
                         driver.quit()
                         return
+                    driver.find_elements(By.XPATH, '//*[@class="HorizontalFeedCard searchPageV2__card"]')
                     num += 1
                     Common.logger(log_type, crawler).info(f'拖动"视频"列表第{num}个至屏幕中间')
                     Common.logging(log_type, crawler, env, f'拖动"视频"列表第{num}个至屏幕中间')