소스 검색

first commit

wangkun 2 년 전
부모
커밋
fd49420ba3

BIN
.DS_Store


+ 3 - 0
.idea/.gitignore

@@ -0,0 +1,3 @@
+# Default ignored files
+/shelf/
+/workspace.xml

+ 12 - 0
.idea/crawler_shipinhao.iml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="PYTHON_MODULE" version="4">
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="jdk" jdkName="Python 3.10" jdkType="Python SDK" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+  <component name="PyDocumentationSettings">
+    <option name="format" value="PLAIN" />
+    <option name="myDocStringFormat" value="Plain" />
+  </component>
+</module>

+ 6 - 0
.idea/inspectionProfiles/profiles_settings.xml

@@ -0,0 +1,6 @@
+<component name="InspectionProjectProfileManager">
+  <settings>
+    <option name="USE_PROJECT_PROFILE" value="false" />
+    <version value="1.0" />
+  </settings>
+</component>

+ 4 - 0
.idea/misc.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10" project-jdk-type="Python SDK" />
+</project>

+ 8 - 0
.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/crawler_shipinhao.iml" filepath="$PROJECT_DIR$/.idea/crawler_shipinhao.iml" />
+    </modules>
+  </component>
+</project>

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
+</project>

+ 23 - 0
README.md

@@ -0,0 +1,23 @@
+# crawler_shipinhao
+
+#### 介绍
+视频号爬虫项目
+
+#### 软件架构
+python==3.10
+Appium_Python_Client==2.6.1
+loguru==0.6.0
+oss2==2.15.0
+requests==2.27.1
+selenium==4.4.3
+urllib3==1.26.9
+
+
+#### 使用说明
+
+1.  cd crawler_shipinhao
+2.  python3 ./main/run_shipinhao_recommend.py
+
+
+
+

BIN
logs/.DS_Store


+ 3 - 0
main/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/9/1

+ 26 - 0
main/click_share_video.py

@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/9/1
+from appium import webdriver
+from selenium.webdriver.common.by import By
+
+
+class Click:
+    @classmethod
+    def click_video(cls):
+        desired_caps = {'app': r"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe"}
+        driver = webdriver.Remote(
+            command_executor='http://127.0.0.1:4723',
+            desired_capabilities=desired_caps)
+        driver.implicitly_wait(10)
+
+        driver.find_element(By.NAME, '爬虫群').click()
+        msg_list = driver.find_elements(By.NAME, '消息')
+        msg = msg_list[-1]
+        title = msg.get_attribute('name')
+        print(title)
+        msg.click()
+
+
+if __name__ == '__main__':
+    Click.click_video()

+ 141 - 0
main/common.py

@@ -0,0 +1,141 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/8/30
+"""
+公共方法,包含:生成log / 删除log / 下载方法 / 读取文件 / 统计下载数
+"""
+from datetime import date, timedelta
+from loguru import logger
+import datetime
+import os
+import time
+import requests
+import urllib3
+proxies = {"http": None, "https": None}
+
+
+class Common:
+    # 统一获取当前时间 <class 'datetime.datetime'>  2022-04-14 20:13:51.244472
+    now = datetime.datetime.now()
+    # 昨天 <class 'str'>  2022-04-13
+    yesterday = (date.today() + timedelta(days=-1)).strftime("%Y-%m-%d")
+    # 今天 <class 'datetime.date'>  2022-04-14
+    today = date.today()
+    # 明天 <class 'str'>  2022-04-15
+    tomorrow = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d")
+
+    # 使用 logger 模块生成日志
+    @staticmethod
+    def logger(log_type):
+        """
+        使用 logger 模块生成日志
+        """
+        # 日志路径
+        log_dir = "./logs/"
+        log_path = os.getcwd() + os.sep + log_dir
+        if not os.path.isdir(log_path):
+            os.makedirs(log_path)
+
+        # 日志文件名
+        if log_type == "recommend":
+            log_name = time.strftime("%Y-%m-%d", time.localtime(time.time())) + '-shipinhao-recommend.log'
+        elif log_type == "follow":
+            log_name = time.strftime("%Y-%m-%d", time.localtime(time.time())) + '-shipinhao-follow.log'
+        else:
+            log_name = time.strftime("%Y-%m-%d", time.localtime(time.time())) + '-shipinhao.log'
+
+        # 日志不打印到控制台
+        logger.remove(handler_id=None)
+
+        # rotation="500 MB",实现每 500MB 存储一个文件
+        # rotation="12:00",实现每天 12:00 创建一个文件
+        # rotation="1 week",每周创建一个文件
+        # retention="10 days",每隔10天之后就会清理旧的日志
+        # 初始化日志
+        logger.add(log_dir + log_name, level="INFO", rotation='00:00')
+
+        return logger
+
+    # 清除日志,保留最近 6 个文件
+    @classmethod
+    def del_logs(cls, log_type):
+        """
+        清除冗余日志文件
+        :d_dir: 需要删除的 log 地址
+        :return: 保留最近 6 个日志
+        """
+        logs_dir = "./logs/"
+        if not os.path.exists(logs_dir):
+            os.mkdir(logs_dir)
+
+        all_files = sorted(os.listdir(logs_dir))
+        all_logs = []
+        for log in all_files:
+            name = os.path.splitext(log)[-1]
+            if name == ".log":
+                all_logs.append(log)
+
+        if len(all_logs) <= 6:
+            pass
+        else:
+            for file in all_logs[:len(all_logs) - 6]:
+                os.remove(logs_dir + file)
+        cls.logger(log_type).info("清除冗余日志成功\n")
+
+    # 封装下载视频或封面的方法
+    @classmethod
+    def download_method(cls, log_type, text, d_name, d_url):
+        """
+        下载封面:text == "cover" ; 下载视频:text == "video"
+        需要下载的视频标题:d_title
+        视频封面,或视频播放地址:d_url
+        下载保存路径:"./files/{d_title}/"
+        """
+        videos_dir = "./videos/"
+        if not os.path.exists(videos_dir):
+            os.mkdir(videos_dir)
+        # 首先创建一个保存该视频相关信息的文件夹
+        video_dir = "./videos/" + d_name + "/"
+        if not os.path.exists(video_dir):
+            os.mkdir(video_dir)
+
+        # 下载视频
+        if text == "video":
+            # 需要下载的视频地址
+            video_url = d_url
+            # 视频名
+            video_name = "video.mp4"
+
+            # 下载视频
+            urllib3.disable_warnings()
+            response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
+            try:
+                with open(video_dir + video_name, "wb") as f:
+                    for chunk in response.iter_content(chunk_size=10240):
+                        f.write(chunk)
+                cls.logger(log_type).info("==========视频下载完成==========")
+            except Exception as e:
+                cls.logger(log_type).exception("视频下载失败:{}\n", e)
+
+        # 下载封面
+        elif text == "cover":
+            # 需要下载的封面地址
+            cover_url = d_url
+            # 封面名
+            cover_name = "image.jpg"
+            # # 封面名
+            # cover_name = d_name + ".jpg"
+
+            # 下载封面
+            urllib3.disable_warnings()
+            response = requests.get(cover_url, proxies=proxies, verify=False)
+            try:
+                with open(video_dir + cover_name, "wb") as f:
+                    f.write(response.content)
+                cls.logger(log_type).info("==========封面下载完成==========")
+            except Exception as e:
+                cls.logger(log_type).exception("封面下载失败:{}\n", e)
+
+
+if __name__ == "__main__":
+    common = Common()

+ 83 - 0
main/demo.py

@@ -0,0 +1,83 @@
+# @Author: wangkun
+# @Time: 2月 25, 2022
+import logging
+import os
+import time
+
+path = "../videoinfo/"
+
+
+def read_videoname():
+    with open(path + "videoname.txt", "r", encoding="utf8") as f:
+        content = f.read()
+        name = content
+        return name
+
+
+def write_videoname():
+    n = int(float(read_videoname()))
+    with open(path + "videoname.txt", "w", encoding="utf8") as f:
+        f.write(str(n + 1))
+
+
+def split_text():
+    path1 = "./chlsfiles/"
+    files = os.listdir(path1)
+    for file in files:
+        print(file)
+        print("\n==========\n")
+        a = os.path.splitext(file)
+        print(a[-1])
+
+        # print(file[0])
+        # print(file[-1])
+
+
+def split_query():
+    url = "encfilekey=Cvvj5Ix3eez3Y79SxtvVL0L7CkPM6dFibFeI6caGYwFHPibicjZB7UrwpKsG9wQrl01" \
+          "IlTMtIjicibib9iaGoaL2sxR7vGt4sofODkBGnic9EOCZjgCQTlO7ZTNjribxkDmPq40E2RMdXxzGlWDwYfmkWz4Q15g" \
+          "&token=AxricY7RBHdVbVKZOkvCOWwYWwj9zBqet1eia6GZib8GhmdrytdBu5HcPARtxW7l0AAzppsekDUXXQ&idx=1&adap" \
+          "tivelytrans=943&bizid=1023&dotrans=2991&hy=SH&m=d04052b0ab0e3dd64567fa60b16d0898&scene=0&t=1&taskid=0"
+    a = url.split("encfilekey=")[-1].split("&token=")[0]
+    print(a)
+
+
+def distent():
+    filekey = "Cvvj5Ix3eez3Y79SxtvVL0L7CkPM6dFibFeI6caGYwFEiaKINib2TA0ibV5JuXfIA5JysRWeytU3kTufCr7KFPLgwMiauCic" \
+              "UypoEbA31w7w3sibnraPEwcMcG6LqxSmdFN5S8AfhuibFicv86oBfSuSXcibrCqw"
+    filekey_txt_path = "../videoinfo/filekey.txt"
+
+    with open(filekey_txt_path, 'r', encoding="utf8") as f:
+        content = f.read()
+        print(content)
+        for line in content:
+            if filekey in line.strip():
+                print("yes")
+            elif line.strip() == "":
+                print("null")
+            else:
+                print("no")
+
+
+# 创建日志
+def create_log():
+    # 创建日志文件夹。如果不存在,则创建
+    log_dir = "../logs/"  # 日志文件夹名称
+    log_path = os.getcwd() + os.sep + log_dir  # 日志路径
+    if not os.path.isdir(log_path):
+        os.makedirs(log_path)
+
+    log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+    date_format = "%Y-%m-%d %p %H:%M:%S"
+    # 初始化
+    logging.basicConfig(filename=log_path + 'logs.logs', level=logging.INFO, format=log_format, datefmt=date_format)
+
+    logger = logging.getLogger('shipinhao')
+
+    logger.info("这是第一条日志")
+
+
+if __name__ == "__main__":
+    print(float(str(1.2)))
+
+    pass

+ 17 - 0
main/download_publish.py

@@ -0,0 +1,17 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/9/1
+
+
+class Download:
+    @classmethod
+    def download_publish(cls, log_type, env):
+        pass
+
+    @classmethod
+    def run_download_publish(cls):
+        pass
+
+
+if __name__ == '__main__':
+    Download.download_publish('recommend', 'dev')

+ 313 - 0
main/feishu_lib.py

@@ -0,0 +1,313 @@
+# @Author: wangkun
+# @Time: 3月 08, 2022
+import json
+import requests
+import urllib3
+from main.common import Common
+proxies = {"http": None, "https": None}
+
+
+class Feishu:
+    """
+    编辑飞书云文档
+    """
+    # 看一看爬虫数据表
+    kanyikan_url = "https://w42nne6hzg.feishu.cn/sheets/shtcngRPoDYAi24x52j2nDuHMih?"
+    # 快手爬虫数据表
+    kuaishou_url = "https://w42nne6hzg.feishu.cn/sheets/shtcnp4SaJt37q6OOOrYzPMjQkg?"
+    # 微视爬虫数据表
+    weishi_url = "https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?"
+    # 小年糕爬虫数据表
+    xiaoniangao_url = "https://w42nne6hzg.feishu.cn/sheets/shtcnYxiyQ1wLklo1W5Kdqc9cGh?"
+    # 数据监控表
+    crawler_monitor = "https://w42nne6hzg.feishu.cn/sheets/shtcnlZWYazInhf7Z60jkbLRJyd?"
+    # 本山祝福数据表
+    crawler_benshanzhufu = "https://w42nne6hzg.feishu.cn/sheets/shtcnGh2rrsPYM4iVNEBO7OqWrb?"
+    # 公众号爬虫表
+    gzh_url = "https://w42nne6hzg.feishu.cn/sheets/shtcnexNXnpDLHhARw0QdiwbYuA?"
+    # 视频号表
+    shipinhao_url = 'https://w42nne6hzg.feishu.cn/sheets/shtcn9rOdZRAGFbRkWpn7hqEHGc?'
+
+    # 飞书路径token
+    @classmethod
+    def spreadsheettoken(cls, crawler):
+        """
+        :param crawler: 哪个爬虫
+        """
+        if crawler == "kanyikan":
+            return "shtcngRPoDYAi24x52j2nDuHMih"
+        elif crawler == "kuaishou":
+            return "shtcnp4SaJt37q6OOOrYzPMjQkg"
+        elif crawler == "weishi":
+            return "shtcn5YSWg91JfVGzj0SFZIRRPh"
+        elif crawler == "xiaoniangao":
+            return "shtcnYxiyQ1wLklo1W5Kdqc9cGh"
+        elif crawler == "monitor":
+            return "shtcnlZWYazInhf7Z60jkbLRJyd"
+        elif crawler == "bszf":
+            return "shtcnGh2rrsPYM4iVNEBO7OqWrb"
+        elif crawler == "gzh":
+            return "shtcnexNXnpDLHhARw0QdiwbYuA"
+        elif crawler == "shipinhao":
+            return "shtcn9rOdZRAGFbRkWpn7hqEHGc"
+
+    # 获取飞书api token
+    @classmethod
+    def get_token(cls, log_type):
+        """
+        获取飞书api token
+        :return:
+        """
+        url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
+        post_data = {"app_id": "cli_a13ad2afa438d00b",  # 这里账号密码是发布应用的后台账号及密码
+                     "app_secret": "4tK9LY9VbiQlY5umhE42dclBFo6t4p5O"}
+
+        try:
+            urllib3.disable_warnings()
+            response = requests.post(url=url, data=post_data, proxies=proxies, verify=False)
+            tenant_access_token = response.json()["tenant_access_token"]
+            return tenant_access_token
+        except Exception as e:
+            Common.logger(log_type).error("获取飞书 api token 异常:{}", e)
+
+    # 获取表格元数据
+    @classmethod
+    def get_metainfo(cls, log_type, crawler):
+        """
+        获取表格元数据
+        :return:
+        """
+        get_metainfo_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                           + cls.spreadsheettoken(crawler) + "/metainfo"
+
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        params = {
+            "extFields": "protectedRange",  # 额外返回的字段,extFields=protectedRange时返回保护行列信息
+            "user_id_type": "open_id"  # 返回的用户id类型,可选open_id,union_id
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.get(url=get_metainfo_url, headers=headers, params=params, proxies=proxies, verify=False)
+            response = json.loads(r.content.decode("utf8"))
+            return response
+        except Exception as e:
+            Common.logger(log_type).error("获取表格元数据异常:{}", e)
+
+    # 读取工作表中所有数据
+    @classmethod
+    def get_values_batch(cls, log_type, crawler, sheetid):
+        """
+        读取工作表中所有数据
+        :param log_type: 启用哪个 log
+        :param crawler: 哪个爬虫
+        :param sheetid: 哪张表
+        :return: 所有数据
+        """
+        get_values_batch_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                               + cls.spreadsheettoken(crawler) + "/values_batch_get"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        params = {
+            # 多个查询范围 如 url?ranges=range1,range2 ,其中 range 包含 sheetId 与单元格范围两部分
+            "ranges": sheetid,
+
+            # valueRenderOption=ToString 可返回纯文本的值(数值类型除外);
+            # valueRenderOption=FormattedValue 计算并格式化单元格;
+            # valueRenderOption=Formula单元格中含有公式时返回公式本身;
+            # valueRenderOption=UnformattedValue计算但不对单元格进行格式化
+            "valueRenderOption": "ToString",
+
+            # dateTimeRenderOption=FormattedString 计算并将时间日期按照其格式进行格式化,但不会对数字进行格式化,返回格式化后的字符串。
+            "dateTimeRenderOption": "",
+
+            # 返回的用户id类型,可选open_id,union_id
+            "user_id_type": "open_id"
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.get(url=get_values_batch_url, headers=headers, params=params, proxies=proxies, verify=False)
+            # print(r.text)
+            response = json.loads(r.content.decode("utf8"))
+            values = response["data"]["valueRanges"][0]["values"]
+            return values
+        except Exception as e:
+            Common.logger(log_type).error("读取工作表所有数据异常:{}", e)
+
+    # 工作表,插入行或列
+    @classmethod
+    def insert_columns(cls, log_type, crawler, sheetid, majordimension, startindex, endindex):
+        """
+        工作表插入行或列
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫的云文档
+        :param sheetid:哪张工作表
+        :param majordimension:行或者列, ROWS、COLUMNS
+        :param startindex:开始位置
+        :param endindex:结束位置
+        """
+        insert_columns_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                             + cls.spreadsheettoken(crawler) + "/insert_dimension_range"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        body = {
+            "dimension": {
+                "sheetId": sheetid,
+                "majorDimension": majordimension,  # 默认 ROWS ,可选 ROWS、COLUMNS
+                "startIndex": startindex,  # 开始的位置
+                "endIndex": endindex  # 结束的位置
+            },
+            "inheritStyle": "AFTER"  # BEFORE 或 AFTER,不填为不继承 style
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.post(url=insert_columns_url, headers=headers, json=body, proxies=proxies, verify=False)
+            Common.logger(log_type).info("插入行或列:{}", r.json()["msg"])
+        except Exception as e:
+            Common.logger(log_type).error("插入行或列异常:{}", e)
+
+    # 写入数据
+    @classmethod
+    def update_values(cls, log_type, crawler, sheetid, ranges, values):
+        """
+        写入数据
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫的云文档
+        :param sheetid:哪张工作表
+        :param ranges:单元格范围
+        :param values:写入的具体数据,list
+        """
+        update_values_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                            + cls.spreadsheettoken(crawler) + "/values_batch_update"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        body = {
+            "valueRanges": [
+                {
+                    "range": sheetid + "!" + ranges,
+                    "values": values
+                },
+            ],
+        }
+
+        try:
+            urllib3.disable_warnings()
+            r = requests.post(url=update_values_url, headers=headers, json=body, proxies=proxies, verify=False)
+            Common.logger(log_type).info("写入数据:{}", r.json()["msg"])
+        except Exception as e:
+            Common.logger(log_type).error("写入数据异常:{}", e)
+
+    # 合并单元格
+    @classmethod
+    def merge_cells(cls, log_type, crawler, sheetid, ranges):
+        """
+        合并单元格
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫
+        :param sheetid:哪张工作表
+        :param ranges:需要合并的单元格范围
+        """
+        merge_cells_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                          + cls.spreadsheettoken(crawler) + "/merge_cells"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+
+        body = {
+            "range": sheetid + "!" + ranges,
+            "mergeType": "MERGE_ROWS"
+        }
+
+        try:
+            urllib3.disable_warnings()
+            r = requests.post(url=merge_cells_url, headers=headers, json=body, proxies=proxies, verify=False)
+            Common.logger(log_type).info("合并单元格:{}", r.json()["msg"])
+        except Exception as e:
+            Common.logger(log_type).error("合并单元格异常:{}", e)
+
+    # 读取单元格数据
+    @classmethod
+    def get_range_value(cls, log_type, crawler, sheetid, cell):
+        """
+        读取单元格内容
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫
+        :param sheetid: 哪张工作表
+        :param cell: 哪个单元格
+        :return: 单元格内容
+        """
+        get_range_value_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                              + cls.spreadsheettoken(crawler) + "/values/" + sheetid + "!" + cell
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        params = {
+            # valueRenderOption=ToString 可返回纯文本的值(数值类型除外);
+            # valueRenderOption=FormattedValue 计算并格式化单元格;
+            # valueRenderOption=Formula 单元格中含有公式时返回公式本身;
+            # valueRenderOption=UnformattedValue 计算但不对单元格进行格式化。
+            "valueRenderOption": "FormattedValue",
+
+            # dateTimeRenderOption=FormattedString 计算并对时间日期按照其格式进行格式化,但不会对数字进行格式化,返回格式化后的字符串。
+            "dateTimeRenderOption": "",
+
+            # 返回的用户id类型,可选open_id,union_id
+            "user_id_type": "open_id"
+        }
+        try:
+            urllib3.disable_warnings()
+            r = requests.get(url=get_range_value_url, headers=headers, params=params, proxies=proxies, verify=False)
+            # print(r.text)
+            return r.json()["data"]["valueRange"]["values"][0]
+        except Exception as e:
+            Common.logger(log_type).error("读取单元格数据异常:{}", e)
+
+    # 删除行或列,可选 ROWS、COLUMNS
+    @classmethod
+    def dimension_range(cls, log_type, crawler, sheetid, major_dimension, startindex, endindex):
+        """
+        删除行或列
+        :param log_type: 日志路径
+        :param crawler: 哪个爬虫
+        :param sheetid:工作表
+        :param major_dimension:默认 ROWS ,可选 ROWS、COLUMNS
+        :param startindex:开始的位置
+        :param endindex:结束的位置
+        :return:
+        """
+        dimension_range_url = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/" \
+                              + cls.spreadsheettoken(crawler) + "/dimension_range"
+        headers = {
+            "Authorization": "Bearer " + cls.get_token(log_type),
+            "Content-Type": "application/json; charset=utf-8"
+        }
+        body = {
+            "dimension": {
+                "sheetId": sheetid,
+                "majorDimension": major_dimension,
+                "startIndex": startindex,
+                "endIndex": endindex
+                }
+            }
+        try:
+            urllib3.disable_warnings()
+            r = requests.delete(url=dimension_range_url, headers=headers, json=body, proxies=proxies, verify=False)
+            Common.logger(log_type).info("删除视频数据:{}", r.json()["msg"])
+        except Exception as e:
+            Common.logger(log_type).error("删除视频数据异常:{}", e)
+
+
+if __name__ == "__main__":
+    print(Feishu.get_token('gzh'))
+
+    pass

+ 13 - 0
main/get_url.py

@@ -0,0 +1,13 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/9/1
+
+
+class GetUrl:
+    @classmethod
+    def get_url(cls):
+        pass
+
+
+if __name__ == '__main__':
+    GetUrl.get_url()

+ 252 - 0
main/publish.py

@@ -0,0 +1,252 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/9/1
+import json
+import os
+import random
+import time
+import oss2
+import requests
+import urllib3
+from main.common import Common
+proxies = {"http": None, "https": None}
+
+
+class Publish:
+    @classmethod
+    def publish_video_dev(cls, log_type, request_data):
+        """
+        loginUid  站内uid (随机)
+        appType  默认:888888
+        crawlerSrcId   站外视频ID
+        crawlerSrcCode   渠道(自定义 KYK)
+        crawlerSrcPublishTimestamp  视频原发布时间
+        crawlerTaskTimestamp   爬虫创建时间(可以是当前时间)
+        videoPath  视频oss地址
+        coverImgPath  视频封面oss地址
+        title  标题
+        totalTime  视频时长
+        viewStatus  视频的有效状态 默认1
+        versionCode  版本 默认1
+        :return:
+        """
+        # Common.logger().info('publish request data: {}'.format(request_data))
+        result = cls.request_post('https://videotest.yishihui.com/longvideoapi/crawler/video/send', request_data)
+        # Common.logger(log_type).info('publish result: {}'.format(result))
+        video_id = result["data"]["id"]
+        # Common.logger(log_type).info('video_id: {}'.format(video_id))
+        if result['code'] != 0:
+            Common.logger(log_type).error('pushlish failure msg = {}'.format(result['msg']))
+        else:
+            Common.logger(log_type).info('publish success video_id = : {}'.format(request_data['crawlerSrcId']))
+        return video_id
+
+    @classmethod
+    def publish_video_prod(cls, log_type, request_data):
+        """
+        loginUid  站内uid (随机)
+        appType  默认:888888
+        crawlerSrcId   站外视频ID
+        crawlerSrcCode   渠道(自定义 KYK)
+        crawlerSrcPublishTimestamp  视频原发布时间
+        crawlerTaskTimestamp   爬虫创建时间(可以是当前时间)
+        videoPath  视频oss地址
+        coverImgPath  视频封面oss地址
+        title  标题
+        totalTime  视频时长
+        viewStatus  视频的有效状态 默认1
+        versionCode  版本 默认1
+        :return:
+        """
+        result = cls.request_post('https://longvideoapi.piaoquantv.com/longvideoapi/crawler/video/send', request_data)
+        # Common.logger(log_type).info('publish result: {}'.format(result))
+        video_id = result["data"]["id"]
+        # Common.logger(log_type).info('video_id: {}'.format(video_id))
+        if result['code'] != 0:
+            Common.logger(log_type).error('pushlish failure msg = {}'.format(result['msg']))
+        else:
+            Common.logger(log_type).info('publish success video_id = : {}'.format(request_data['crawlerSrcId']))
+        return video_id
+
+    @classmethod
+    def request_post(cls, request_url, request_data):
+        """
+        post 请求 HTTP接口
+        :param request_url: 接口URL
+        :param request_data: 请求参数
+        :return: res_data json格式
+        """
+        urllib3.disable_warnings()
+        response = requests.post(url=request_url, data=request_data, proxies=proxies, verify=False)
+        if response.status_code == 200:
+            res_data = json.loads(response.text)
+            return res_data
+
+    # 以下代码展示了基本的文件上传、下载、罗列、删除用法。
+
+    # 首先初始化AccessKeyId、AccessKeySecret、Endpoint等信息。
+    # 通过环境变量获取,或者把诸如“<你的AccessKeyId>”替换成真实的AccessKeyId等。
+    #
+    # 以杭州区域为例,Endpoint可以是:
+    #   http://oss-cn-hangzhou.aliyuncs.com
+    #   https://oss-cn-hangzhou.aliyuncs.com
+    # 分别以HTTP、HTTPS协议访问。
+    access_key_id = os.getenv('OSS_TEST_ACCESS_KEY_ID', 'LTAIP6x1l3DXfSxm')
+    access_key_secret = os.getenv('OSS_TEST_ACCESS_KEY_SECRET', 'KbTaM9ars4OX3PMS6Xm7rtxGr1FLon')
+    bucket_name = os.getenv('OSS_TEST_BUCKET', 'art-pubbucket')
+    # endpoint = os.getenv('OSS_TEST_ENDPOINT', 'oss-cn-hangzhou-internal.aliyuncs.com')
+    endpoint = os.getenv('OSS_TEST_ENDPOINT', 'oss-cn-hangzhou.aliyuncs.com')
+
+    # 确认上面的参数都填写正确了
+    for param in (access_key_id, access_key_secret, bucket_name, endpoint):
+        assert '<' not in param, '请设置参数:' + param
+
+    # 创建Bucket对象,所有Object相关的接口都可以通过Bucket对象来进行
+    bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)
+
+    """
+    处理流程:
+    1. 定时(每天凌晨1点执行一次)循环files文件下的内容 结构:files -> 视频文件夹 -> 视频文件 + 封面图 + 基本信息
+    2. 视频文件和封面上传到oss
+    - 视频文件oss目录  longvideo/crawler_local/video/prod/文件名
+    - 视频封面oss目录  longvideo/crawler_local/image/prod/文件名
+    3. 发布视频
+    - 读取 基本信息 调用发布接口
+    """
+    # env 日期20220225 文件名
+    oss_file_path_video = 'longvideo/crawler_local/video/{}/{}/{}'
+    oss_file_path_image = 'longvideo/crawler_local/image/{}/{}/{}'
+
+    @classmethod
+    def put_file(cls, log_type, oss_file, local_file):
+        cls.bucket.put_object_from_file(oss_file, local_file)
+        Common.logger(log_type).info("put oss file = {}, local file = {} success".format(oss_file, local_file))
+
+    # 清除本地文件
+    @classmethod
+    def remove_local_file(cls, log_type, local_file):
+        os.remove(local_file)
+        Common.logger(log_type).info("remove local file = {} success".format(local_file))
+
+    # 清除本地文件夹
+    @classmethod
+    def remove_local_file_dir(cls, log_type, local_file):
+        os.rmdir(local_file)
+        Common.logger(log_type).info("remove local file dir = {} success".format(local_file))
+
+    local_file_path = './videos'
+    video_file = 'video'
+    image_file = 'image'
+    info_file = 'info'
+    uids_dev_up = [6267140]
+    uids_dev_play = [6267141]
+    uids_prod_up = [20631248, 20631249, 20631250, 20631251, 20631252]
+    uids_prod_play = [20631248, 20631249, 20631250, 20631251, 20631252]
+
+    @classmethod
+    def upload_and_publish(cls, log_type, env, job):
+        """
+        上传视频到 oss
+        :param log_type: 选择的 log
+        :param env: 测试环境:dev,正式环境:prod
+        :param job: 上升榜:up,播放量:play
+        """
+        Common.logger(log_type).info("upload_and_publish starting...")
+        today = time.strftime("%Y%m%d", time.localtime())
+        # videos 目录下的所有视频文件夹
+        files = os.listdir(cls.local_file_path)
+        for f in files:
+            try:
+                # 单个视频文件夹
+                fi_d = os.path.join(cls.local_file_path, f)
+                # 确认为视频文件夹
+                if os.path.isdir(fi_d):
+                    Common.logger(log_type).info('dir = {}'.format(fi_d))
+                    # 列出所有视频文件夹
+                    dir_files = os.listdir(fi_d)
+                    data = {'appType': '888888',
+                            'crawlerSrcCode': 'SHIPINHAO',
+                            'viewStatus': '1',
+                            'versionCode': '1'}
+                    now_timestamp = int(round(time.time() * 1000))
+                    data['crawlerTaskTimestamp'] = str(now_timestamp)
+                    global uid
+                    if env == "dev" and job == "up":
+                        uid = str(random.choice(cls.uids_dev_up))
+                    elif env == "dev" and job == "play":
+                        uid = str(random.choice(cls.uids_dev_play))
+                    elif env == "prod" and job == "up":
+                        uid = str(random.choice(cls.uids_prod_up))
+                    elif env == "prod" and job == "play":
+                        uid = str(random.choice(cls.uids_prod_play))
+                    data['loginUid'] = uid
+                    # 单个视频文件夹下的所有视频文件
+                    for fi in dir_files:
+                        # 视频文件夹下的所有文件路径
+                        fi_path = fi_d + '/' + fi
+                        Common.logger(log_type).info('dir fi_path = {}'.format(fi_path))
+                        # 读取 info.txt,赋值给 data
+                        if cls.info_file in fi:
+                            f = open(fi_path, "r", encoding="UTF-8")
+                            # 读取数据 数据准确性写入的时候保证 读取暂不处理
+                            for i in range(14):
+                                line = f.readline()
+                                line = line.replace('\n', '')
+                                if line is not None and len(line) != 0 and not line.isspace():
+                                    # Common.logger(log_type).info("line = {}".format(line))
+                                    if i == 0:
+                                        data['crawlerSrcId'] = line
+                                    elif i == 1:
+                                        data['title'] = line
+                                    elif i == 2:
+                                        data['totalTime'] = line
+                                    elif i == 8:
+                                        data['crawlerSrcPublishTimestamp'] = line
+                                else:
+                                    Common.logger(log_type).warning("{} line is None".format(fi_path))
+                            f.close()
+                            # remove info.txt
+                            cls.remove_local_file(log_type, fi_path)
+                    # 刷新数据
+                    dir_files = os.listdir(fi_d)
+                    for fi in dir_files:
+                        fi_path = fi_d + '/' + fi
+                        # Common.logger(log_type).info('dir fi_path = {}'.format(fi_path))
+                        # 上传oss
+                        if cls.video_file in fi:
+                            global oss_video_file
+                            if env == "dev":
+                                oss_video_file = cls.oss_file_path_video.format("dev", today, data['crawlerSrcId'])
+                            elif env == "prod":
+                                oss_video_file = cls.oss_file_path_video.format("prod", today, data['crawlerSrcId'])
+                            Common.logger(log_type).info("oss_video_file = {}".format(oss_video_file))
+                            cls.put_file(log_type, oss_video_file, fi_path)
+                            data['videoPath'] = oss_video_file
+                            Common.logger(log_type).info("videoPath = {}".format(oss_video_file))
+                        elif cls.image_file in fi:
+                            global oss_image_file
+                            if env == "dev":
+                                oss_image_file = cls.oss_file_path_image.format("env", today, data['crawlerSrcId'])
+                            elif env == "prod":
+                                oss_image_file = cls.oss_file_path_image.format("prod", today, data['crawlerSrcId'])
+                            Common.logger(log_type).info("oss_image_file = {}".format(oss_image_file))
+                            cls.put_file(log_type, oss_image_file, fi_path)
+                            data['coverImgPath'] = oss_image_file
+                            Common.logger(log_type).info("coverImgPath = {}".format(oss_image_file))
+                        # 全部remove
+                        cls.remove_local_file(log_type, fi_path)
+
+                    # 发布
+                    if env == "dev":
+                        video_id = cls.publish_video_dev(log_type, data)
+                    elif env == "prod":
+                        video_id = cls.publish_video_prod(log_type, data)
+                    else:
+                        video_id = cls.publish_video_dev(log_type, data)
+                    cls.remove_local_file_dir(log_type, fi_d)
+                    return video_id
+
+                else:
+                    Common.logger(log_type).error('file not a dir = {}'.format(fi_d))
+            except Exception as e:
+                Common.logger(log_type).exception('upload_and_publish error', e)

+ 23 - 0
main/run_shipinhao_recommend.py

@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+# @Author: wangkun
+# @Time: 2022/8/31
+import os
+import sys
+import time
+
+sys.path.append(os.getcwd())
+from main.common import Common
+from main.shipinhao_recommend import Recommend
+
+
+class Main:
+    @staticmethod
+    def main():
+        for i in range(2):
+            Recommend.start_wechat('recommend')
+            Common.del_logs('recommend')
+            time.sleep(5)
+
+
+if __name__ == '__main__':
+    Main.main()

+ 233 - 0
main/shipinhao_recommend.py

@@ -0,0 +1,233 @@
+# @Author: wangkun
+# @Time: 3月 02, 2022
+import os
+import sys
+import time
+from appium import webdriver
+from appium.webdriver.webdriver import WebDriver
+from selenium.common import NoSuchElementException
+from selenium.webdriver.common.by import By
+sys.path.append(os.getcwd())
+from main.common import Common
+from main.feishu_lib import Feishu
+
+
+class Recommend:
+
+    # 启动微信,并打开视频号
+    @classmethod
+    def start_wechat(cls, log_type):
+        Common.logger(log_type).info('启动微信')
+        caps = {
+            "platformName": "Android",  # 手机操作系统 Android / iOS
+            "deviceName": "Android",  # 连接的设备名(模拟器或真机),安卓可以随便写
+            "platforVersion": "11",  # 手机对应的系统版本(Android 11)
+            "appPackage": "com.tencent.mm",  # 被测APP的包名,乐活圈 Android
+            "appActivity": ".ui.LauncherUI",  # 启动的Activity名
+            "autoGrantPermissions": "true",  # 让 appium 自动授权 base 权限,
+            # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
+            "unicodekeyboard": True,  # 使用自带输入法,输入中文时填True
+            "resetkeyboard": True,  # 执行完程序恢复原来输入法
+            "noReset": True,  # 不重置APP
+            "printPageSourceOnFailure": True,  # 找不到元素时,appium log 会完整记录当前页面的 pagesource
+            "newCommandTimeout": 6000,  # 初始等待时间
+            "automationName": "UiAutomator2"  # 使用引擎,默认为 Appium,
+            # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
+        }
+        # global driver
+        driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
+        driver.implicitly_wait(10)
+
+        Common.logger(log_type).info('点击发现TAB')
+        driver.find_elements(By.ID, 'com.tencent.mm:id/f2s')[2].click()
+
+        Common.logger(log_type).info('点击视频号\n')
+        driver.find_elements(By.ID, 'com.tencent.mm:id/gv6')[1].click()
+        time.sleep(5)
+
+        cls.get_feeds(log_type, driver)
+
+        Common.logger(log_type).info('休眠 3s')
+        time.sleep(3)
+        cls.quit(log_type, driver)
+
+    # 退出 APP
+    @classmethod
+    def quit(cls, log_type, driver: WebDriver):
+        driver.quit()
+        Common.logger(log_type).info('退出 APP 成功\n')
+
+    # 下载规则
+    @staticmethod
+    def download_rule(duration, like_cnt, share_cnt, favorite_cnt, comment_cnt):
+        if int(duration) >= 10:
+            if int(like_cnt) >= 0:
+                if int(share_cnt) >= 0:
+                    if int(favorite_cnt) >= 0:
+                        if int(comment_cnt) >= 0:
+                            return True
+                        else:
+                            return False
+                    else:
+                        return False
+                else:
+                    return False
+            else:
+                return False
+        else:
+            return False
+
+    # 操作安卓手机,自己滑动首页视频,并获取视频信息
+    @classmethod
+    def get_feeds(cls, log_type, driver: WebDriver):
+        driver.implicitly_wait(10)
+        for i in range(10):
+            # 关闭页面弹窗
+            try:
+                driver.find_element(By.XPATH, '//*[@text="我知道了"]')
+                Common.logger(log_type).info('已关闭未成年模式弹窗')
+            except NoSuchElementException:
+                pass
+
+            try:
+                driver.find_element(By.ID, 'com.tencent.mm:id/dkf')
+                Common.logger(log_type).info('直播视频,向上滑动页面\n')
+                driver.swipe(500, 1000, 500, 300, 300)
+            except NoSuchElementException:
+                pass
+
+            # Common.logger(log_type).info('暂停播放')
+            pause_btn = driver.find_element(By.ID, 'com.tencent.mm:id/eh4')
+            pause_btn.click()
+
+            # 视频标题
+            try:
+                title_id = driver.find_element(By.ID, 'com.tencent.mm:id/ki5')
+                video_title = title_id.get_attribute('name')
+            except NoSuchElementException:
+                video_title = ''
+
+            # 点击播放器,获取视频时长
+            start_time = driver.find_element(By.ID, 'com.tencent.mm:id/l59').get_attribute('name')
+            start_time = int(start_time.split(':')[0])*60 + int(start_time.split(':')[-1])
+            try:
+                end_time = driver.find_element(By.ID, 'com.tencent.mm:id/l7i').get_attribute('name')
+            except NoSuchElementException:
+                end_time = driver.find_element(By.ID, 'com.tencent.mm:id/g73').get_attribute('name')
+            end_time = int(end_time.split(':')[0]) * 60 + int(end_time.split(':')[-1])
+            duration = start_time + end_time
+
+            # 点赞
+            like_id = driver.find_element(By.ID, 'com.tencent.mm:id/k04')
+            like_cnt = like_id.get_attribute('name')
+            if like_cnt == "" or like_cnt == "喜欢":
+                like_cnt = 0
+            elif '万' in like_cnt:
+                like_cnt = float(like_cnt.split('万')[0]) * 10000
+            elif '万+' in like_cnt:
+                like_cnt = float(like_cnt.split('万+')[0]) * 10000
+            else:
+                like_cnt = float(like_cnt)
+
+            # 分享
+            share_id = driver.find_element(By.ID, 'com.tencent.mm:id/jhv')
+            share_cnt = share_id.get_attribute('name')
+            if share_cnt == "" or share_cnt == "转发":
+                share_cnt = 0
+            elif '万' in share_cnt:
+                share_cnt = float(share_cnt.split('万')[0]) * 10000
+            elif '万+' in share_cnt:
+                share_cnt = float(share_cnt.split('万+')[0]) * 10000
+            else:
+                share_cnt = float(share_cnt)
+
+            # 收藏
+            favorite_id = driver.find_element(By.ID, 'com.tencent.mm:id/fnp')
+            favorite_cnt = favorite_id.get_attribute('name')
+            if favorite_cnt == "" or favorite_cnt == "收藏":
+                favorite_cnt = 0
+            elif '万' in favorite_cnt:
+                favorite_cnt = float(favorite_cnt.split('万')[0]) * 10000
+            elif '万+' in favorite_cnt:
+                favorite_cnt = float(favorite_cnt.split('万+')[0]) * 10000
+            else:
+                favorite_cnt = float(favorite_cnt)
+
+            # 评论
+            comment_id = driver.find_element(By.ID, 'com.tencent.mm:id/bje')
+            comment_cnt = comment_id.get_attribute('name')
+            if comment_cnt == "" or comment_cnt == "评论":
+                comment_cnt = 0
+            elif '万' in comment_cnt:
+                comment_cnt = float(comment_cnt.split('万')[0]) * 10000
+            elif '万+' in comment_cnt:
+                comment_cnt = float(comment_cnt.split('万+')[0]) * 10000
+            else:
+                comment_cnt = float(comment_cnt)
+
+            # 用户名
+            username_id = driver.find_element(By.ID, 'com.tencent.mm:id/hft')
+            user_name = username_id.get_attribute('name')
+
+            Common.logger(log_type).info('video_title:{}', video_title)
+            Common.logger(log_type).info('duration:{}', duration)
+            Common.logger(log_type).info('like_cnt:{}', like_cnt)
+            Common.logger(log_type).info('share_cnt:{}', share_cnt)
+            Common.logger(log_type).info('favorite_cnt:{}', favorite_cnt)
+            Common.logger(log_type).info('comment_cnt:{}', comment_cnt)
+            Common.logger(log_type).info('user_name:{}', user_name)
+
+            # 判断无效视频
+            if video_title == '' or user_name == '':
+                Common.logger(log_type).info('向上滑动页面')
+                driver.swipe(500, 1000, 500, 300, 300)
+                Common.logger(log_type).info('无效视频\n')
+
+            # 判断下载规则
+            elif cls.download_rule(duration, like_cnt, share_cnt, favorite_cnt, comment_cnt) is False:
+                Common.logger(log_type).info('向上滑动页面')
+                driver.swipe(500, 1000, 500, 300, 300)
+                Common.logger(log_type).info('不满足抓取规则\n')
+
+            # 已下载表去重
+            elif str(video_title) in [x for y in Feishu.get_values_batch(log_type, 'shipinhao', 'c77cf9') for x in y]:
+                Common.logger(log_type).info('向上滑动页面')
+                driver.swipe(500, 1000, 500, 300, 300)
+                Common.logger(log_type).info('视频已下载\n')
+
+            # feeds 表去重
+            elif str(video_title) in [x for y in Feishu.get_values_batch(log_type, 'shipinhao', 'FSDlBy') for x in y]:
+                Common.logger(log_type).info('向上滑动页面')
+                driver.swipe(500, 1000, 500, 300, 300)
+                Common.logger(log_type).info('视频已存在\n')
+
+            # 分享给 windows 爬虫机
+            else:
+                share_id.click()
+                driver.find_element(By.XPATH, '//*[@text="转发给朋友"]').click()
+                driver.find_element(By.XPATH, '//*[@text="爬虫群"]').click()
+                driver.find_element(By.ID, 'com.tencent.mm:id/guw').click()
+
+                # 把视频信息写入飞书feeds文档
+                Feishu.insert_columns(log_type, 'shipinhao', 'FSDlBy', 'ROWS', 1, 2)
+                get_feeds_time = int(time.time())
+                values = [[time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(get_feeds_time)),
+                           '推荐榜',
+                           str(video_title),
+                           duration,
+                           like_cnt,
+                           share_cnt,
+                           favorite_cnt,
+                           comment_cnt,
+                           str(user_name)]]
+                time.sleep(1)
+                Feishu.update_values(log_type, 'shipinhao', 'FSDlBy', 'A2:Z2', values)
+                Common.logger(log_type).info('向上滑动页面')
+                driver.swipe(500, 1000, 500, 300, 300)
+                Common.logger(log_type).info('视频信息写入飞书文档成功\n')
+
+
+if __name__ == '__main__':
+    Recommend.start_wechat('recommend')
+
+    pass

BIN
videos/.DS_Store