gongzhonghao_author.py 28 KB

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