gongzhonghao_follow.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. # from requests.adapters import HTTPAdapter
  13. import requests
  14. import urllib3
  15. from selenium.webdriver import DesiredCapabilities
  16. from selenium.webdriver.chrome.service import Service
  17. from selenium.webdriver.common.by import By
  18. from selenium import webdriver
  19. sys.path.append(os.getcwd())
  20. from common.common import Common
  21. from common.feishu import Feishu
  22. from common.public import get_config_from_mysql
  23. from common.publish import Publish
  24. from common.scheduling_db import MysqlHelper
  25. class GongzhonghaoFollow:
  26. # 翻页参数
  27. begin = 0
  28. platform = "公众号"
  29. # 基础门槛规则
  30. @staticmethod
  31. def download_rule(video_dict):
  32. """
  33. 下载视频的基本规则
  34. :param video_dict: 视频信息,字典格式
  35. :return: 满足规则,返回 True;反之,返回 False
  36. """
  37. # 视频时长 20秒 - 45 分钟
  38. if 60 * 45 >= int(float(video_dict['duration'])) >= 20:
  39. # 宽或高
  40. if int(video_dict['video_width']) >= 0 or int(video_dict['video_height']) >= 0:
  41. return True
  42. else:
  43. return False
  44. else:
  45. return False
  46. @classmethod
  47. def title_like(cls, log_type, crawler, title, env):
  48. select_sql = f""" select * from crawler_video where platform="公众号" """
  49. video_list = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
  50. if len(video_list) == 0:
  51. return None
  52. for video_dict in video_list:
  53. video_title = video_dict["video_title"]
  54. if difflib.SequenceMatcher(None, title, video_title).quick_ratio() >= 0.8:
  55. return True
  56. else:
  57. pass
  58. # 获取 token
  59. @classmethod
  60. def get_token(cls, log_type, crawler):
  61. while True:
  62. # try:
  63. sheet = Feishu.get_values_batch(log_type, crawler, "OjyJqs")
  64. if sheet is None:
  65. time.sleep(1)
  66. continue
  67. token = sheet[0][1]
  68. cookie = sheet[1][1]
  69. gzh_name = sheet[2][1]
  70. gzh_time = sheet[3][1]
  71. token_dict = {'token': token, 'cookie': cookie, 'gzh_name': gzh_name, 'gzh_time': gzh_time}
  72. print(type(token_dict['gzh_time']))
  73. print(token_dict['gzh_time'])
  74. return token_dict
  75. # except Exception as e:
  76. # Common.logger(log_type, crawler).error(f"get_cookie_token异常:{e}\n")
  77. # 获取用户 fakeid
  78. @classmethod
  79. def get_fakeid(cls, log_type, crawler, user, index):
  80. # try:
  81. while True:
  82. token_dict = cls.get_token(log_type, crawler)
  83. url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?"
  84. headers = {
  85. "accept": "*/*",
  86. "accept-encoding": "gzip, deflate, br",
  87. "accept-language": "zh-CN,zh;q=0.9",
  88. "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
  89. "t=media/appmsg_edit_v2&action=edit&isNew=1"
  90. "&type=77&createType=5&token=1011071554&lang=zh_CN",
  91. 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
  92. "sec-ch-ua-mobile": "?0",
  93. "sec-ch-ua-platform": '"Windows"',
  94. "sec-fetch-dest": "empty",
  95. "sec-fetch-mode": "cors",
  96. "sec-fetch-site": "same-origin",
  97. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
  98. " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
  99. "x-requested-with": "XMLHttpRequest",
  100. 'cookie': token_dict['cookie'],
  101. }
  102. params = {
  103. "action": "search_biz",
  104. "begin": "0",
  105. "count": "5",
  106. "query": str(user),
  107. "token": token_dict['token'],
  108. "lang": "zh_CN",
  109. "f": "json",
  110. "ajax": "1",
  111. }
  112. urllib3.disable_warnings()
  113. # s = requests.session()
  114. # # max_retries=3 重试3次
  115. # s.mount('http://', HTTPAdapter(max_retries=3))
  116. # s.mount('https://', HTTPAdapter(max_retries=3))
  117. # r = s.get(url=url, headers=headers, params=params, verify=False, proxies=Common.tunnel_proxies(), timeout=5)
  118. r = requests.get(url=url, headers=headers, params=params, verify=False)
  119. r.close()
  120. if r.json()["base_resp"]["err_msg"] == "invalid session":
  121. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  122. Common.logger(log_type, crawler).warning(f"get_fakeid:{r.text}\n")
  123. Common.logger(log_type, crawler).warning(f"token_1:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 过期啦\n")
  124. if 20 >= datetime.datetime.now().hour >= 10:
  125. Feishu.bot(log_type, crawler, f"token_1:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
  126. time.sleep(60 * 10)
  127. continue
  128. if r.json()["base_resp"]["err_msg"] == "freq control":
  129. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  130. Common.logger(log_type, crawler).warning(f"get_fakeid:{r.text}\n")
  131. Common.logger(log_type, crawler).warning(f"公众号_1:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 频控啦\n")
  132. if 20 >= datetime.datetime.now().hour >= 10:
  133. Feishu.bot(log_type, crawler, f"公众号_1:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
  134. time.sleep(60 * 10)
  135. continue
  136. if "list" not in r.json() or len(r.json()["list"]) == 0:
  137. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  138. Common.logger(log_type, crawler).warning(f"get_fakeid:{r.text}\n")
  139. Common.logger(log_type, crawler).warning(f"公众号_1:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 频控啦\n")
  140. if 20 >= datetime.datetime.now().hour >= 10:
  141. Feishu.bot(log_type, crawler, f"公众号_1:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
  142. time.sleep(60 * 10)
  143. continue
  144. fakeid = r.json()["list"][int(index) - 1]["fakeid"]
  145. head_url = r.json()["list"][int(index) - 1]["round_head_img"]
  146. fakeid_dict = {'fakeid': fakeid, 'head_url': head_url}
  147. return fakeid_dict
  148. # except Exception as e:
  149. # Common.logger(log_type, crawler).error(f"get_fakeid异常:{e}\n")
  150. # 获取腾讯视频下载链接
  151. @classmethod
  152. def get_tencent_video_url(cls, video_id):
  153. # try:
  154. url = 'https://vv.video.qq.com/getinfo?vids=' + str(video_id) + '&platform=101001&charge=0&otype=json'
  155. response = requests.get(url=url).text.replace('QZOutputJson=', '').replace('"};', '"}')
  156. response = json.loads(response)
  157. url = response['vl']['vi'][0]['ul']['ui'][0]['url']
  158. fvkey = response['vl']['vi'][0]['fvkey']
  159. video_url = url + str(video_id) + '.mp4?vkey=' + fvkey
  160. return video_url
  161. # except Exception as e:
  162. # Common.logger(log_type, crawler).error(f"get_tencent_video_url异常:{e}\n")
  163. @classmethod
  164. def get_video_url(cls, article_url, env):
  165. # try:
  166. # 打印请求配置
  167. ca = DesiredCapabilities.CHROME
  168. ca["goog:loggingPrefs"] = {"performance": "ALL"}
  169. # 不打开浏览器运行
  170. chrome_options = webdriver.ChromeOptions()
  171. chrome_options.add_argument("headless")
  172. chrome_options.add_argument(
  173. 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')
  174. chrome_options.add_argument("--no-sandbox")
  175. # driver初始化
  176. if env == "prod":
  177. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
  178. else:
  179. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service(
  180. '/Users/wangkun/Downloads/chromedriver/chromedriver_v111/chromedriver'))
  181. driver.implicitly_wait(10)
  182. # Common.logger(log_type, crawler).info('打开文章链接')
  183. driver.get(article_url)
  184. time.sleep(1)
  185. if len(driver.find_elements(By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]')) != 0:
  186. video_url = driver.find_element(
  187. By.XPATH, '//div[@class="js_video_poster video_poster"]/*[2]').get_attribute('src')
  188. elif len(driver.find_elements(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]')) != 0:
  189. iframe = driver.find_element(By.XPATH, '//span[@class="js_tx_video_container"]/*[1]').get_attribute(
  190. 'src')
  191. video_id = iframe.split('vid=')[-1].split('&')[0]
  192. video_url = cls.get_tencent_video_url(video_id)
  193. else:
  194. video_url = 0
  195. driver.quit()
  196. return video_url
  197. # except Exception as e:
  198. # Common.logger(log_type, crawler).info(f'get_video_url异常:{e}\n')
  199. # 获取文章列表
  200. @classmethod
  201. def get_videoList(cls, log_type, crawler, user, index, oss_endpoint, env):
  202. # try:
  203. while True:
  204. token_dict = cls.get_token(log_type, crawler)
  205. fakeid_dict = cls.get_fakeid(log_type, crawler, user, index)
  206. url = "https://mp.weixin.qq.com/cgi-bin/appmsg?"
  207. headers = {
  208. "accept": "*/*",
  209. "accept-encoding": "gzip, deflate, br",
  210. "accept-language": "zh-CN,zh;q=0.9",
  211. "referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?"
  212. "t=media/appmsg_edit_v2&action=edit&isNew=1"
  213. "&type=77&createType=5&token=" + str(token_dict['token']) + "&lang=zh_CN",
  214. 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
  215. "sec-ch-ua-mobile": "?0",
  216. "sec-ch-ua-platform": '"Windows"',
  217. "sec-fetch-dest": "empty",
  218. "sec-fetch-mode": "cors",
  219. "sec-fetch-site": "same-origin",
  220. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
  221. " (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
  222. "x-requested-with": "XMLHttpRequest",
  223. 'cookie': token_dict['cookie'],
  224. }
  225. params = {
  226. "action": "list_ex",
  227. "begin": str(cls.begin),
  228. "count": "5",
  229. "fakeid": fakeid_dict['fakeid'],
  230. "type": "9",
  231. "query": "",
  232. "token": str(token_dict['token']),
  233. "lang": "zh_CN",
  234. "f": "json",
  235. "ajax": "1",
  236. }
  237. urllib3.disable_warnings()
  238. # s = requests.session()
  239. # # max_retries=3 重试3次
  240. # s.mount('http://', HTTPAdapter(max_retries=3))
  241. # s.mount('https://', HTTPAdapter(max_retries=3))
  242. # r = s.get(url=url, headers=headers, params=params, verify=False, proxies=Common.tunnel_proxies(), timeout=5)
  243. r = requests.get(url=url, headers=headers, params=params, verify=False)
  244. r.close()
  245. if r.json()["base_resp"]["err_msg"] == "invalid session":
  246. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  247. Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
  248. Common.logger(log_type, crawler).warning(
  249. f"token_1:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 过期啦\n")
  250. if 20 >= datetime.datetime.now().hour >= 10:
  251. Feishu.bot(log_type, crawler, f"token_1:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n过期啦,请扫码更换token\nhttps://mp.weixin.qq.com/")
  252. time.sleep(60 * 10)
  253. continue
  254. if r.json()["base_resp"]["err_msg"] == "freq control":
  255. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  256. Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
  257. Common.logger(log_type, crawler).warning(
  258. f"公众号_1:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 频控啦\n")
  259. if 20 >= datetime.datetime.now().hour >= 10:
  260. Feishu.bot(log_type, crawler,f"公众号_1:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
  261. time.sleep(60 * 10)
  262. continue
  263. if 'app_msg_list' not in r.json():
  264. Common.logger(log_type, crawler).warning(f"status_code:{r.status_code}")
  265. Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
  266. Common.logger(log_type, crawler).warning(
  267. f"公众号_1:{token_dict['gzh_name']}, 更换日期:{token_dict['gzh_time']} 频控啦\n")
  268. if 20 >= datetime.datetime.now().hour >= 10:
  269. Feishu.bot(log_type, crawler, f"公众号_1:{token_dict['gzh_name']}\n更换日期:{token_dict['gzh_time']}\n频控啦,请扫码更换其他公众号token\nhttps://mp.weixin.qq.com/")
  270. time.sleep(60 * 10)
  271. continue
  272. if len(r.json()['app_msg_list']) == 0:
  273. Common.logger(log_type, crawler).info('没有更多视频了\n')
  274. return
  275. else:
  276. cls.begin += 5
  277. app_msg_list = r.json()['app_msg_list']
  278. for article_url in app_msg_list:
  279. # title
  280. if 'title' in article_url:
  281. title = article_url['title'].replace('/', '').replace('\n', '') \
  282. .replace('.', '').replace('“', '').replace('”', '').replace(' ', '')\
  283. .replace('"', '').replace("'", "")
  284. else:
  285. title = 0
  286. # aid
  287. if 'aid' in article_url:
  288. aid = article_url['aid']
  289. else:
  290. aid = 0
  291. # create_time
  292. if 'create_time' in article_url:
  293. create_time = article_url['create_time']
  294. else:
  295. create_time = 0
  296. publish_time_stamp = int(create_time)
  297. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  298. avatar_url = fakeid_dict['head_url']
  299. # cover_url
  300. if 'cover' in article_url:
  301. cover_url = article_url['cover']
  302. else:
  303. cover_url = 0
  304. # article_url
  305. if 'link' in article_url:
  306. article_url = article_url['link']
  307. else:
  308. article_url = 0
  309. video_url = cls.get_video_url(article_url, env)
  310. video_dict = {
  311. 'video_id': aid,
  312. 'video_title': title,
  313. 'publish_time_stamp': publish_time_stamp,
  314. 'publish_time_str': publish_time_str,
  315. 'user_name': user,
  316. 'play_cnt': 0,
  317. 'comment_cnt': 0,
  318. 'like_cnt': 0,
  319. 'share_cnt': 0,
  320. 'user_id': fakeid_dict['fakeid'],
  321. 'avatar_url': avatar_url,
  322. 'cover_url': cover_url,
  323. 'article_url': article_url,
  324. 'video_url': video_url,
  325. 'session': f'gongzhonghao-follow-{int(time.time())}'
  326. }
  327. for k, v in video_dict.items():
  328. Common.logger(log_type, crawler).info(f"{k}:{v}")
  329. if int(time.time()) - publish_time_stamp > 3600 * 24 * 2:
  330. Common.logger(log_type, crawler).info(f'发布时间{publish_time_str} > 2 天\n')
  331. cls.begin = 0
  332. return
  333. cls.download_publish(log_type, crawler, video_dict, oss_endpoint, env)
  334. Common.logger(log_type, crawler).info('休眠 60 秒\n')
  335. time.sleep(60)
  336. # except Exception as e:
  337. # Common.logger(log_type, crawler).error(f"get_videoList异常:{e}\n")
  338. @classmethod
  339. def repeat_video(cls, log_type, crawler, video_id, env):
  340. sql = f""" select * from crawler_video where platform="公众号" and out_video_id="{video_id}"; """
  341. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  342. return len(repeat_video)
  343. # 下载/上传
  344. @classmethod
  345. def download_publish(cls, log_type, crawler, video_dict, oss_endpoint, env):
  346. # try:
  347. if video_dict['article_url'] == 0 or video_dict['video_url'] == 0:
  348. Common.logger(log_type, crawler).info("文章涉嫌违反相关法律法规和政策\n")
  349. # 标题敏感词过滤
  350. elif any(word if word in video_dict['video_title']
  351. else False for word in get_config_from_mysql(log_type=log_type,
  352. source=crawler,
  353. env=env,
  354. text="filter",
  355. action="")) is True:
  356. Common.logger(log_type, crawler).info("标题已中过滤词\n")
  357. # 已下载判断
  358. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env) != 0:
  359. Common.logger(log_type, crawler).info("视频已下载\n")
  360. # 标题相似度
  361. elif cls.title_like(log_type, crawler, video_dict['video_title'], env) is True:
  362. Common.logger(log_type, crawler).info(f'标题相似度>=80%:{video_dict["video_title"]}\n')
  363. else:
  364. # 下载视频
  365. Common.download_method(log_type=log_type, crawler=crawler, text="video",
  366. title=video_dict["video_title"], url=video_dict["video_url"])
  367. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  368. # 获取视频时长
  369. ffmpeg_dict = Common.ffmpeg(log_type, crawler,
  370. f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  371. if ffmpeg_dict is None:
  372. # 删除视频文件夹
  373. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  374. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  375. return
  376. video_dict["video_width"] = ffmpeg_dict["width"]
  377. video_dict["video_height"] = ffmpeg_dict["height"]
  378. video_dict["duration"] = ffmpeg_dict["duration"]
  379. video_size = ffmpeg_dict["size"]
  380. Common.logger(log_type, crawler).info(f'video_width:{video_dict["video_width"]}')
  381. Common.logger(log_type, crawler).info(f'video_height:{video_dict["video_height"]}')
  382. Common.logger(log_type, crawler).info(f'duration:{video_dict["duration"]}')
  383. Common.logger(log_type, crawler).info(f'video_size:{video_size}')
  384. # 视频size=0,直接删除
  385. if int(video_size) == 0 or cls.download_rule(video_dict) is False:
  386. # 删除视频文件夹
  387. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  388. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  389. return
  390. # 下载封面
  391. Common.download_method(log_type=log_type, crawler=crawler, text="cover",
  392. title=video_dict["video_title"], url=video_dict["cover_url"])
  393. # 保存视频信息至 "./videos/{video_title}/info.txt"
  394. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  395. # 上传视频
  396. Common.logger(log_type, crawler).info("开始上传视频...")
  397. strategy = "定向爬虫策略"
  398. our_video_id = Publish.upload_and_publish(log_type=log_type,
  399. crawler=crawler,
  400. strategy=strategy,
  401. our_uid="follow",
  402. oss_endpoint=oss_endpoint,
  403. env=env)
  404. if env == 'prod':
  405. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
  406. else:
  407. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{str(our_video_id)}/info"
  408. Common.logger(log_type, crawler).info("视频上传完成")
  409. if our_video_id is None:
  410. # 删除视频文件夹
  411. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  412. return
  413. # 视频信息保存数据库
  414. rule_dict = {
  415. "duration": {"min": 20, "max": 45 * 60},
  416. "publish_day": {"min": 3}
  417. }
  418. insert_sql = f""" insert into crawler_video(video_id,
  419. out_user_id,
  420. platform,
  421. strategy,
  422. out_video_id,
  423. video_title,
  424. cover_url,
  425. video_url,
  426. duration,
  427. publish_time,
  428. play_cnt,
  429. crawler_rule,
  430. width,
  431. height)
  432. values({our_video_id},
  433. "{video_dict['user_id']}",
  434. "{cls.platform}",
  435. "定向爬虫策略",
  436. "{video_dict['video_id']}",
  437. "{video_dict['video_title']}",
  438. "{video_dict['cover_url']}",
  439. "{video_dict['video_url']}",
  440. {int(video_dict['duration'])},
  441. "{video_dict['publish_time_str']}",
  442. {int(video_dict['play_cnt'])},
  443. '{json.dumps(rule_dict)}',
  444. {int(video_dict['video_width'])},
  445. {int(video_dict['video_height'])}) """
  446. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  447. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  448. Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
  449. # 视频写入飞书
  450. Feishu.insert_columns(log_type, crawler, "47e39d", "ROWS", 1, 2)
  451. # 视频ID工作表,首行写入数据
  452. upload_time = int(time.time())
  453. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  454. "用户主页",
  455. video_dict['video_title'],
  456. video_dict['video_id'],
  457. our_video_link,
  458. int(video_dict['duration']),
  459. f"{video_dict['video_width']}*{video_dict['video_height']}",
  460. video_dict['publish_time_str'],
  461. video_dict['user_name'],
  462. video_dict['user_id'],
  463. video_dict['avatar_url'],
  464. video_dict['cover_url'],
  465. video_dict['article_url'],
  466. video_dict['video_url']]]
  467. time.sleep(0.5)
  468. Feishu.update_values(log_type, crawler, "47e39d", "F2:Z2", values)
  469. Common.logger(log_type, crawler).info('视频下载/上传成功\n')
  470. # except Exception as e:
  471. # Common.logger(log_type, crawler).error(f"download_publish异常:{e}\n")
  472. @classmethod
  473. def get_users(cls):
  474. # user_sheet = Feishu.get_values_batch("follow", 'gongzhonghao', 'Bzv72P')
  475. # user_list = []
  476. # # for i in range(1, len(user_sheet)):
  477. # for i in range(1, 101):
  478. # user_name = user_sheet[i][0]
  479. # index = user_sheet[i][1]
  480. # user_dict = {
  481. # "user_name": user_name,
  482. # "index": index,
  483. # }
  484. # user_list.append(user_dict)
  485. # print(len(user_list))
  486. # print(user_list)
  487. user_list = [{'user_name': '香音难忘', 'index': 1}, {'user_name': '墨儿心灵驿站', 'index': 1}, {'user_name': '荒烟茶生', 'index': 1}, {'user_name': '幸福花朵', 'index': 1}, {'user_name': '我的节日祝福', 'index': 1}, {'user_name': '生活创意妙招', 'index': 1}, {'user_name': '二大妈有话说', 'index': 1}, {'user_name': '医路健康美食', 'index': 1}, {'user_name': '老年相知相伴', 'index': 1}, {'user_name': '一争', 'index': 1}, {'user_name': '老年企退群', 'index': 1}, {'user_name': '消逝的哨声', 'index': 1}, {'user_name': '一颗打破石头的蛋', 'index': 1}, {'user_name': '叩问苍穹荒烟茶生', 'index': 1}, {'user_name': '布衣星火', 'index': 1}, {'user_name': '叩问苍穹', 'index': 1}, {'user_name': '微观调查', 'index': 2}, {'user_name': '传统节日祝福', 'index': 1}, {'user_name': '因和德尚', 'index': 1}, {'user_name': '飨宴心灵', 'index': 1}, {'user_name': '朝闻解局', 'index': 1}, {'user_name': '远见光芒', 'index': 1}, {'user_name': '墨儿微刊', 'index': 1}, {'user_name': '博爱论', 'index': 1}, {'user_name': '张大春讲堂', 'index': 1}, {'user_name': ' 司马南频道', 'index': 1}, {'user_name': '音乐小镇', 'index': 1}, {'user_name': '节日祝福365', 'index': 1}, {'user_name': '动画音乐相册', 'index': 1}, {'user_name': '音乐动漫相册', 'index': 1}, {'user_name': '早点谈健康', 'index': 1}, {'user_name': '早点谈养生', 'index': 1}, {'user_name': '早点谈养身', 'index': 1}, {'user_name': '医道谈养身', 'index': 1}, {'user_name': '中老年谈养身', 'index': 1}, {'user_name': '尼古拉斯瞭望', 'index': 1}, {'user_name': '奇易时光百姓的福音', 'index': 1}, {'user_name': '寰宇时光', 'index': 1}, {'user_name': '红兴文化公苑', 'index': 1}, {'user_name': '早点音乐', 'index': 1}, {'user_name': '小分子生物活性肽', 'index': 1}, {'user_name': '张小妹美食', 'index': 1}, {'user_name': '万物归息', 'index': 1}, {'user_name': '神州红魂', 'index': 1}, {'user_name': '音乐早餐', 'index': 1}, {'user_name': '1条末读消息', 'index': 1}, {'user_name': '环球文摘', 'index': 1}, {'user_name': '精彩有余', 'index': 1}, {'user_name': '一起训练吧', 'index': 1}, {'user_name': '1条重要消息', 'index': 1}, {'user_name': '太上养身', 'index': 1}, {'user_name': '懂点养身秘诀', 'index': 1}, {'user_name': '送乐者', 'index': 1}, {'user_name': '蜂业小百科', 'index': 1}, {'user_name': '健康与养身秘诀', 'index': 1}, {'user_name': '有心人r', 'index': 1}, {'user_name': '古诗词世界', 'index': 1}, {'user_name': '晨间悦读', 'index': 1}, {'user_name': '养身有诀窍', 'index': 1}, {'user_name': '退休族信息圈', 'index': 1}, {'user_name': '艾公铁粉团', 'index': 1}, {'user_name': '酸甜苦辣麻咸', 'index': 1}, {'user_name': '日常生活小帮手', 'index': 1}, {'user_name': '小帅的精彩视频', 'index': 1}, {'user_name': '养身常识小窍门', 'index': 1}, {'user_name': '医学养身技巧', 'index': 1}, {'user_name': '退休圈', 'index': 1}, {'user_name': '生活小助手', 'index': 1}, {'user_name': '经典老歌曲好听的音乐', 'index': 1}, {'user_name': '黑马快讯', 'index': 1}, {'user_name': '绝妙经典', 'index': 1}, {'user_name': '深读时策', 'index': 1}, {'user_name': '健康与生活大全', 'index': 1}, {'user_name': '李肃论道', 'index': 1}, {'user_name': '爱国者吹锋号', 'index': 1}, {'user_name': '兵心可鉴', 'index': 1}, {'user_name': '精选动心金曲', 'index': 1}, {'user_name': '爱二胡群', 'index': 1}, {'user_name': '数码科技大爆炸', 'index': 1}, {'user_name': '何静同学', 'index': 1}, {'user_name': '方敏爱美食', 'index': 1}, {'user_name': '针灸推拿特色技术', 'index': 1}, {'user_name': '挺进天山', 'index': 1}, {'user_name': '紫陌捻花', 'index': 1}, {'user_name': '巨响养身', 'index': 1}, {'user_name': '荣观世界', 'index': 1}, {'user_name': 'Music音乐世界', 'index': 1}, {'user_name': '微观调查组', 'index': 1}, {'user_name': '用汉方拥抱世界', 'index': 1}, {'user_name': '医学养身秘诀', 'index': 1}, {'user_name': '医学老人养身', 'index': 1}, {'user_name': '热文微观', 'index': 1}, {'user_name': '医学养身秘笈', 'index': 1}, {'user_name': '你未读消息', 'index': 1}, {'user_name': '零点相聚', 'index': 2}, {'user_name': '观念颠覆一切', 'index': 1}, {'user_name': '侯老师说食疗精选', 'index': 1}, {'user_name': '侯老师说食疗', 'index': 1}, {'user_name': '今日看点收集', 'index': 1}, {'user_name': '君拍', 'index': 1}]
  488. return user_list
  489. @classmethod
  490. def get_all_videos(cls, log_type, crawler, oss_endpoint, env):
  491. user_list = cls.get_users()
  492. for user_dict in user_list:
  493. try:
  494. user_name = user_dict['user_name']
  495. index = user_dict['index']
  496. Common.logger(log_type, crawler).info(f'获取 {user_name} 公众号视频\n')
  497. cls.get_videoList(log_type, crawler, user_name, index, oss_endpoint, env)
  498. cls.begin = 0
  499. Common.logger(log_type, crawler).info('休眠 60 秒\n')
  500. time.sleep(60)
  501. except Exception as e:
  502. Common.logger(log_type, crawler).info(f'get_all_videos异常:{e}\n')
  503. if __name__ == "__main__":
  504. # GongzhonghaoFollow.get_token(log_type="follow", crawler="gongzhonghao")
  505. # GongzhonghaoFollow.get_users()
  506. # GongzhonghaoFollow.get_videoList(log_type="follow",
  507. # crawler="gongzhonghao",
  508. # user="香音难忘",
  509. # index=1,
  510. # oss_endpoint="out",
  511. # env="dev")
  512. print(get_config_from_mysql(log_type="test",
  513. source="gongzhonghao",
  514. env="prod",
  515. text="filter",
  516. action=""))
  517. pass