gongzhonghao_author.py 29 KB

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