gongzhonghao2_author.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/3/28
  4. import datetime
  5. import difflib
  6. import json
  7. import os
  8. import shutil
  9. import sys
  10. import time
  11. from hashlib import md5
  12. import requests
  13. import urllib3
  14. from selenium.webdriver import DesiredCapabilities
  15. from selenium.webdriver.chrome.service import Service
  16. from selenium.webdriver.common.by import By
  17. from selenium import webdriver
  18. sys.path.append(os.getcwd())
  19. from common.common import Common
  20. from common.feishu import Feishu
  21. from common.publish import Publish
  22. from common.scheduling_db import MysqlHelper
  23. from common.public import get_config_from_mysql
  24. class GongzhonghaoAuthor2:
  25. # 翻页参数
  26. begin = 0
  27. platform = "公众号"
  28. # 基础门槛规则
  29. @staticmethod
  30. def download_rule(log_type, crawler, video_dict, rule_dict):
  31. """
  32. 下载视频的基本规则
  33. :param log_type: 日志
  34. :param crawler: 哪款爬虫
  35. :param video_dict: 视频信息,字典格式
  36. :param rule_dict: 规则信息,字典格式
  37. :return: 满足规则,返回 True;反之,返回 False
  38. """
  39. rule_play_cnt_min = rule_dict.get('play_cnt', {}).get('min', 0)
  40. rule_play_cnt_max = rule_dict.get('play_cnt', {}).get('max', 100000000)
  41. if rule_play_cnt_max == 0:
  42. rule_play_cnt_max = 100000000
  43. rule_duration_min = rule_dict.get('duration', {}).get('min', 0)
  44. rule_duration_max = rule_dict.get('duration', {}).get('max', 100000000)
  45. if rule_duration_max == 0:
  46. rule_duration_max = 100000000
  47. rule_period_min = rule_dict.get('period', {}).get('min', 0)
  48. # rule_period_max = rule_dict.get('period', {}).get('max', 100000000)
  49. # if rule_period_max == 0:
  50. # rule_period_max = 100000000
  51. # rule_fans_cnt_min = rule_dict.get('fans_cnt', {}).get('min', 0)
  52. # rule_fans_cnt_max = rule_dict.get('fans_cnt', {}).get('max', 100000000)
  53. # if rule_fans_cnt_max == 0:
  54. # rule_fans_cnt_max = 100000000
  55. # rule_videos_cnt_min = rule_dict.get('videos_cnt', {}).get('min', 0)
  56. # rule_videos_cnt_max = rule_dict.get('videos_cnt', {}).get('max', 100000000)
  57. # if rule_videos_cnt_max == 0:
  58. # rule_videos_cnt_max = 100000000
  59. rule_like_cnt_min = rule_dict.get('like_cnt', {}).get('min', 0)
  60. rule_like_cnt_max = rule_dict.get('like_cnt', {}).get('max', 100000000)
  61. if rule_like_cnt_max == 0:
  62. rule_like_cnt_max = 100000000
  63. # rule_width_min = rule_dict.get('width', {}).get('min', 0)
  64. # rule_width_max = rule_dict.get('width', {}).get('max', 100000000)
  65. # if rule_width_max == 0:
  66. # rule_width_max = 100000000
  67. #
  68. # rule_height_min = rule_dict.get('height', {}).get('min', 0)
  69. # rule_height_max = rule_dict.get('height', {}).get('max', 100000000)
  70. # if rule_height_max == 0:
  71. # rule_height_max = 100000000
  72. rule_share_cnt_min = rule_dict.get('share_cnt', {}).get('min', 0)
  73. rule_share_cnt_max = rule_dict.get('share_cnt', {}).get('max', 100000000)
  74. if rule_share_cnt_max == 0:
  75. rule_share_cnt_max = 100000000
  76. rule_comment_cnt_min = rule_dict.get('comment_cnt', {}).get('min', 0)
  77. rule_comment_cnt_max = rule_dict.get('comment_cnt', {}).get('max', 100000000)
  78. if rule_comment_cnt_max == 0:
  79. rule_comment_cnt_max = 100000000
  80. Common.logger(log_type, crawler).info(f'rule_duration_max:{rule_duration_max} >= duration:{int(float(video_dict["duration"]))} >= rule_duration_min:{int(rule_duration_min)}')
  81. Common.logger(log_type, crawler).info(f'rule_play_cnt_max:{int(rule_play_cnt_max)} >= play_cnt:{int(video_dict["play_cnt"])} >= rule_play_cnt_min:{int(rule_play_cnt_min)}')
  82. Common.logger(log_type, crawler).info(f'now:{int(time.time())} - publish_time_stamp:{int(video_dict["publish_time_stamp"])} <= {3600 * 24 * int(rule_period_min)}')
  83. Common.logger(log_type, crawler).info(f'rule_like_cnt_max:{int(rule_like_cnt_max)} >= like_cnt:{int(video_dict["like_cnt"])} >= rule_like_cnt_min:{int(rule_like_cnt_min)}')
  84. Common.logger(log_type, crawler).info(f'rule_comment_cnt_max:{int(rule_comment_cnt_max)} >= comment_cnt:{int(video_dict["comment_cnt"])} >= rule_comment_cnt_min:{int(rule_comment_cnt_min)}')
  85. Common.logger(log_type, crawler).info(f'rule_share_cnt_max:{int(rule_share_cnt_max)} >= share_cnt:{int(video_dict["share_cnt"])} >= rule_share_cnt_min:{int(rule_share_cnt_min)}')
  86. if int(rule_duration_max) >= int(float(video_dict["duration"])) >= int(rule_duration_min) \
  87. and int(rule_play_cnt_max) >= int(video_dict['play_cnt']) >= int(rule_play_cnt_min) \
  88. and int(time.time()) - int(video_dict["publish_time_stamp"]) <= 3600 * 24 * int(rule_period_min) \
  89. and int(rule_like_cnt_max) >= int(video_dict['like_cnt']) >= int(rule_like_cnt_min) \
  90. and int(rule_comment_cnt_max) >= int(video_dict['comment_cnt']) >= int(rule_comment_cnt_min) \
  91. and int(rule_share_cnt_max) >= int(video_dict['share_cnt']) >= int(rule_share_cnt_min):
  92. return True
  93. else:
  94. return False
  95. @classmethod
  96. def title_like(cls, log_type, crawler, title, env):
  97. select_sql = f""" select * from crawler_video where platform="公众号" """
  98. video_list = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
  99. if len(video_list) == 0:
  100. return None
  101. for video_dict in video_list:
  102. video_title = video_dict["video_title"]
  103. if difflib.SequenceMatcher(None, title, video_title).quick_ratio() >= 0.8:
  104. return True
  105. else:
  106. pass
  107. # 获取 token
  108. @classmethod
  109. def get_token(cls, log_type, crawler, env):
  110. select_sql = f""" select * from crawler_config where source="{crawler}" and title LIKE "%公众号_2%";"""
  111. configs = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
  112. if len(configs) == 0:
  113. # Common.logger(log_type, crawler).warning(f"公众号_2未配置token")
  114. Feishu.bot(log_type, crawler, "公众号_2:未配置token")
  115. return None
  116. token_dict = {
  117. "token_id": configs[0]["id"],
  118. "title": configs[0]["title"],
  119. "token": dict(eval(configs[0]["config"]))["token"],
  120. "cookie": dict(eval(configs[0]["config"]))["cookie"],
  121. "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(configs[0]["update_time"]/1000))),
  122. "operator": configs[0]["operator"]
  123. }
  124. for k, v in token_dict.items():
  125. print(f"{k}:{v}")
  126. return token_dict
  127. # 获取用户 fakeid
  128. @classmethod
  129. def get_fakeid(cls, log_type, crawler, wechat_name, env):
  130. while True:
  131. token_dict = cls.get_token(log_type, crawler, env)
  132. url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
  133. headers = {
  134. "accept": "*/*",
  135. "accept-encoding": "gzip, deflate, br",
  136. "accept-language": "zh-CN,zh;q=0.9",
  137. "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
  138. "t=media/appmsg_edit_v2&action=edit&isNew=1"
  139. "&type=77&createType=5&token=1011071554&lang=zh_CN",
  140. 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
  141. "sec-ch-ua-mobile": "?0",
  142. "sec-ch-ua-platform": '"Windows"',
  143. "sec-fetch-dest": "empty",
  144. "sec-fetch-mode": "cors",
  145. "sec-fetch-site": "same-origin",
  146. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
  147. " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
  148. "x-requested-with": "XMLHttpRequest",
  149. 'cookie': token_dict['cookie'],
  150. }
  151. params = {
  152. "action": "search_biz",
  153. "begin": "0",
  154. "count": "5",
  155. "query": str(wechat_name),
  156. "token": token_dict['token'],
  157. "lang": "zh_CN",
  158. "f": "json",
  159. "ajax": "1",
  160. }
  161. urllib3.disable_warnings()
  162. r = requests.get(url=url, headers=headers, params=params, verify=False)
  163. r.close()
  164. if r.json()["base_resp"]["err_msg"] == "invalid session":
  165. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  166. Common.logger(log_type, crawler).warning(f"get_fakeid:{r.text}\n")
  167. # Common.logger(log_type, crawler).warning(f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} 过期啦\n")
  168. if 20 >= datetime.datetime.now().hour >= 10:
  169. Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
  170. time.sleep(60 * 10)
  171. continue
  172. if r.json()["base_resp"]["err_msg"] == "freq control":
  173. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  174. Common.logger(log_type, crawler).warning(f"get_fakeid:{r.text}\n")
  175. # Common.logger(log_type, crawler).warning(f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} 频控啦\n")
  176. if 20 >= datetime.datetime.now().hour >= 10:
  177. Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
  178. time.sleep(60 * 10)
  179. continue
  180. if "list" not in r.json() or len(r.json()["list"]) == 0:
  181. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  182. Common.logger(log_type, crawler).warning(f"get_fakeid:{r.text}\n")
  183. # Common.logger(log_type, crawler).warning(f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} 频控啦\n")
  184. if 20 >= datetime.datetime.now().hour >= 10:
  185. Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
  186. time.sleep(60 * 10)
  187. continue
  188. fakeid = r.json()["list"][0]["fakeid"]
  189. head_url = r.json()["list"][0]["round_head_img"]
  190. fakeid_dict = {'fakeid': fakeid, 'head_url': head_url}
  191. return fakeid_dict
  192. # 获取腾讯视频下载链接
  193. @classmethod
  194. def get_tencent_video_url(cls, video_id):
  195. # try:
  196. url = 'https://vv.video.qq.com/getinfo?vids=' + str(video_id) + '&platform=101001&charge=0&otype=json'
  197. response = requests.get(url=url).text.replace('QZOutputJson=', '').replace('"};', '"}')
  198. response = json.loads(response)
  199. url = response['vl']['vi'][0]['ul']['ui'][0]['url']
  200. fvkey = response['vl']['vi'][0]['fvkey']
  201. video_url = url + str(video_id) + '.mp4?vkey=' + fvkey
  202. return video_url
  203. # except Exception as e:
  204. # Common.logger(log_type, crawler).error(f"get_tencent_video_url异常:{e}\n")
  205. @classmethod
  206. def get_video_url(cls, article_url, env):
  207. # try:
  208. # 打印请求配置
  209. ca = DesiredCapabilities.CHROME
  210. ca["goog:loggingPrefs"] = {"performance": "ALL"}
  211. # 不打开浏览器运行
  212. chrome_options = webdriver.ChromeOptions()
  213. chrome_options.add_argument("headless")
  214. chrome_options.add_argument(
  215. f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36')
  216. chrome_options.add_argument("--no-sandbox")
  217. # driver初始化
  218. if env == "prod":
  219. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
  220. else:
  221. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service(
  222. '/Users/wangkun/Downloads/chromedriver/chromedriver_v111/chromedriver'))
  223. driver.implicitly_wait(10)
  224. # Common.logger(log_type, crawler).info('打开文章链接')
  225. driver.get(article_url)
  226. time.sleep(1)
  227. if len(driver.find_elements(By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]')) != 0:
  228. video_url = driver.find_element(
  229. By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]').get_attribute('src')
  230. elif len(driver.find_elements(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]')) != 0:
  231. iframe = driver.find_element(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]').get_attribute(
  232. 'src')
  233. video_id = iframe.split('vid=')[-1].split('&')[0]
  234. video_url = cls.get_tencent_video_url(video_id)
  235. else:
  236. video_url = 0
  237. driver.quit()
  238. return video_url
  239. # except Exception as e:
  240. # Common.logger(log_type, crawler).info(f'get_video_url异常:{e}\n')
  241. # 获取文章列表
  242. @classmethod
  243. def get_videoList(cls, log_type, crawler, wechat_name, rule_dict, user_name, uid, oss_endpoint, env):
  244. # try:
  245. while True:
  246. token_dict = cls.get_token(log_type, crawler, env)
  247. fakeid_dict = cls.get_fakeid(log_type=log_type,
  248. crawler=crawler,
  249. wechat_name=wechat_name,
  250. env=env)
  251. url = "https://mp.weixin.qq.com/cgi-bin/appmsg?"
  252. headers = {
  253. "accept": "*/*",
  254. "accept-encoding": "gzip, deflate, br",
  255. "accept-language": "zh-CN,zh;q=0.9",
  256. "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
  257. "t=media/appmsg_edit_v2&action=edit&isNew=1"
  258. "&type=77&createType=5&token=" + str(token_dict['token']) + "&lang=zh_CN",
  259. 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
  260. "sec-ch-ua-mobile": "?0",
  261. "sec-ch-ua-platform": '"Windows"',
  262. "sec-fetch-dest": "empty",
  263. "sec-fetch-mode": "cors",
  264. "sec-fetch-site": "same-origin",
  265. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
  266. " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
  267. "x-requested-with": "XMLHttpRequest",
  268. 'cookie': token_dict['cookie'],
  269. }
  270. params = {
  271. "action": "list_ex",
  272. "begin": str(cls.begin),
  273. "count": "5",
  274. "fakeid": fakeid_dict['fakeid'],
  275. "type": "9",
  276. "query": "",
  277. "token": str(token_dict['token']),
  278. "lang": "zh_CN",
  279. "f": "json",
  280. "ajax": "1",
  281. }
  282. urllib3.disable_warnings()
  283. r = requests.get(url=url, headers=headers, params=params, verify=False)
  284. r.close()
  285. if r.json()["base_resp"]["err_msg"] == "invalid session":
  286. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  287. Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
  288. # Common.logger(log_type, crawler).warning(f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} 过期啦\n")
  289. if 20 >= datetime.datetime.now().hour >= 10:
  290. Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
  291. time.sleep(60 * 10)
  292. continue
  293. if r.json()["base_resp"]["err_msg"] == "freq control":
  294. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  295. Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
  296. # Common.logger(log_type, crawler).warning(f"{token_dict['title']}, 操作人:{token_dict['operator']}, 更换日期:{token_dict['update_time']} 频控啦\n")
  297. if 20 >= datetime.datetime.now().hour >= 10:
  298. Feishu.bot(log_type, crawler,f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} \n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
  299. time.sleep(60 * 10)
  300. continue
  301. if 'app_msg_list' not in r.json():
  302. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  303. Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
  304. # Common.logger(log_type, crawler).warning(f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']} 频控啦\n")
  305. if 20 >= datetime.datetime.now().hour >= 10:
  306. Feishu.bot(log_type, crawler, f"{token_dict['title']}\n操作人:{token_dict['operator']}\n更换日期:{token_dict['update_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
  307. time.sleep(60 * 10)
  308. continue
  309. if len(r.json()['app_msg_list']) == 0:
  310. Common.logger(log_type, crawler).info('没有更多视频了\n')
  311. return
  312. else:
  313. cls.begin += 5
  314. app_msg_list = r.json()['app_msg_list']
  315. for article_url in app_msg_list:
  316. # title
  317. video_title = article_url.get("title", "").replace('/', '').replace('\n', '') \
  318. .replace('.', '').replace('“', '').replace('”', '').replace(' ', '')\
  319. .replace('"', '').replace("'", "")
  320. # aid
  321. aid = article_url.get('aid', '')
  322. # create_time
  323. create_time = article_url.get('create_time', 0)
  324. publish_time_stamp = int(create_time)
  325. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  326. avatar_url = fakeid_dict['head_url']
  327. # cover_url
  328. cover_url = article_url.get('cover', '')
  329. # article_url
  330. article_url = article_url.get('link', '')
  331. video_url = cls.get_video_url(article_url, env)
  332. video_dict = {
  333. 'video_id': aid,
  334. 'video_title': video_title,
  335. 'publish_time_stamp': publish_time_stamp,
  336. 'publish_time_str': publish_time_str,
  337. 'user_name': user_name,
  338. 'play_cnt': 0,
  339. 'comment_cnt': 0,
  340. 'like_cnt': 0,
  341. 'share_cnt': 0,
  342. 'user_id': fakeid_dict['fakeid'],
  343. 'avatar_url': avatar_url,
  344. 'cover_url': cover_url,
  345. 'article_url': article_url,
  346. 'video_url': video_url,
  347. 'session': f'gongzhonghao-author1-{int(time.time())}'
  348. }
  349. for k, v in video_dict.items():
  350. Common.logger(log_type, crawler).info(f"{k}:{v}")
  351. if int(time.time()) - publish_time_stamp > 3600 * 24 * int(rule_dict.get('period', {}).get('min', 1000)):
  352. Common.logger(log_type, crawler).info(f"发布时间超过{int(rule_dict.get('period', {}).get('min', 1000))}天\n")
  353. cls.begin = 0
  354. return
  355. if video_dict['article_url'] == 0 or video_dict['video_url'] == 0:
  356. Common.logger(log_type, crawler).info("文章涉嫌违反相关法律法规和政策\n")
  357. # 标题敏感词过滤
  358. elif any(str(word) if str(word) in video_dict['video_title'] else False
  359. for word in get_config_from_mysql(log_type=log_type,
  360. source=crawler,
  361. env=env,
  362. text="filter",
  363. action="")) is True:
  364. Common.logger(log_type, crawler).info("标题已中过滤词\n")
  365. # 已下载判断
  366. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env) != 0:
  367. Common.logger(log_type, crawler).info("视频已下载\n")
  368. # 标题相似度
  369. elif cls.title_like(log_type, crawler, video_dict['video_title'], env) is True:
  370. Common.logger(log_type, crawler).info(f'标题相似度>=80%:{video_dict["video_title"]}\n')
  371. else:
  372. cls.download_publish(log_type=log_type,
  373. crawler=crawler,
  374. video_dict=video_dict,
  375. rule_dict=rule_dict,
  376. uid=uid,
  377. oss_endpoint=oss_endpoint,
  378. env=env)
  379. Common.logger(log_type, crawler).info('休眠 60 秒\n')
  380. time.sleep(60)
  381. @classmethod
  382. def repeat_video(cls, log_type, crawler, video_id, env):
  383. sql = f""" select * from crawler_video where platform="公众号" and out_video_id="{video_id}"; """
  384. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  385. return len(repeat_video)
  386. # 下载/上传
  387. @classmethod
  388. def download_publish(cls, log_type, crawler, video_dict, rule_dict, uid, oss_endpoint, env):
  389. # 下载视频
  390. Common.download_method(log_type=log_type, crawler=crawler, text="video",
  391. title=video_dict["video_title"], url=video_dict["video_url"])
  392. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  393. # 获取视频时长
  394. ffmpeg_dict = Common.ffmpeg(log_type, crawler,
  395. f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  396. if ffmpeg_dict is None:
  397. # 删除视频文件夹
  398. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  399. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  400. return
  401. video_dict["video_width"] = ffmpeg_dict["width"]
  402. video_dict["video_height"] = ffmpeg_dict["height"]
  403. video_dict["duration"] = ffmpeg_dict["duration"]
  404. video_size = ffmpeg_dict["size"]
  405. Common.logger(log_type, crawler).info(f'video_width:{video_dict["video_width"]}')
  406. Common.logger(log_type, crawler).info(f'video_height:{video_dict["video_height"]}')
  407. Common.logger(log_type, crawler).info(f'duration:{video_dict["duration"]}')
  408. Common.logger(log_type, crawler).info(f'video_size:{video_size}')
  409. # 视频size=0,直接删除
  410. if int(video_size) == 0 or cls.download_rule(log_type, crawler, video_dict, rule_dict) is False:
  411. # 删除视频文件夹
  412. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  413. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  414. return
  415. # 下载封面
  416. Common.download_method(log_type=log_type, crawler=crawler, text="cover",
  417. title=video_dict["video_title"], url=video_dict["cover_url"])
  418. # 保存视频信息至 "./videos/{video_title}/info.txt"
  419. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  420. # 上传视频
  421. Common.logger(log_type, crawler).info("开始上传视频...")
  422. strategy = "定向榜爬虫策略"
  423. our_video_id = Publish.upload_and_publish(log_type=log_type,
  424. crawler=crawler,
  425. strategy=strategy,
  426. our_uid=uid,
  427. oss_endpoint=oss_endpoint,
  428. env=env)
  429. if env == 'prod':
  430. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
  431. else:
  432. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
  433. Common.logger(log_type, crawler).info("视频上传完成")
  434. if our_video_id is None:
  435. # 删除视频文件夹
  436. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  437. return
  438. insert_sql = f""" insert into crawler_video(video_id,
  439. out_user_id,
  440. platform,
  441. strategy,
  442. out_video_id,
  443. video_title,
  444. cover_url,
  445. video_url,
  446. duration,
  447. publish_time,
  448. play_cnt,
  449. crawler_rule,
  450. width,
  451. height)
  452. values({our_video_id},
  453. "{video_dict['user_id']}",
  454. "{cls.platform}",
  455. "定向爬虫策略",
  456. "{video_dict['video_id']}",
  457. "{video_dict['video_title']}",
  458. "{video_dict['cover_url']}",
  459. "{video_dict['video_url']}",
  460. {int(video_dict['duration'])},
  461. "{video_dict['publish_time_str']}",
  462. {int(video_dict['play_cnt'])},
  463. '{json.dumps(rule_dict)}',
  464. {int(video_dict['video_width'])},
  465. {int(video_dict['video_height'])}) """
  466. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  467. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  468. Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
  469. # 视频写入飞书
  470. Feishu.insert_columns(log_type, crawler, "47e39d", "ROWS", 1, 2)
  471. # 视频ID工作表,首行写入数据
  472. upload_time = int(time.time())
  473. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  474. "用户主页",
  475. video_dict['video_title'],
  476. video_dict['video_id'],
  477. our_video_link,
  478. int(video_dict['duration']),
  479. f"{video_dict['video_width']}*{video_dict['video_height']}",
  480. video_dict['publish_time_str'],
  481. video_dict['user_name'],
  482. video_dict['user_id'],
  483. video_dict['avatar_url'],
  484. video_dict['cover_url'],
  485. video_dict['article_url'],
  486. video_dict['video_url']]]
  487. time.sleep(0.5)
  488. Feishu.update_values(log_type, crawler, "47e39d", "F2:Z2", values)
  489. Common.logger(log_type, crawler).info('视频下载/上传成功\n')
  490. @classmethod
  491. def get_all_videos(cls, log_type, crawler, user_list, rule_dict, oss_endpoint, env):
  492. if len(user_list) == 0:
  493. Common.logger(log_type, crawler).warning(f"抓取用户列表为空\n")
  494. return
  495. for user in user_list:
  496. # try:
  497. user_name = user['nick_name']
  498. wechat_name = user['link']
  499. uid = user['uid']
  500. Common.logger(log_type, crawler).info(f'获取 {user_name} 公众号视频\n')
  501. cls.get_videoList(log_type=log_type,
  502. crawler=crawler,
  503. wechat_name=wechat_name,
  504. rule_dict=rule_dict,
  505. user_name=user_name,
  506. uid=uid,
  507. oss_endpoint=oss_endpoint,
  508. env=env)
  509. cls.begin = 0
  510. Common.logger(log_type, crawler).info('休眠 60 秒\n')
  511. time.sleep(60)
  512. # except Exception as e:
  513. # Common.logger(log_type, crawler).info(f'get_all_videos异常:{e}\n')
  514. if __name__ == "__main__":
  515. GongzhonghaoAuthor2.get_token("author", "gongzhonghao", "dev")
  516. # print(get_config_from_mysql("author", "gongzhonghao", "dev", "filter", action=""))
  517. pass