follow_dy.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. # -*- coding: utf-8 -*-
  2. # @Author: lierqiang
  3. # @Time: 2023/4/12
  4. import json
  5. import os
  6. import random
  7. import shutil
  8. import sys
  9. import time
  10. import requests
  11. from hashlib import md5
  12. sys.path.append(os.getcwd())
  13. from douyin.douyin_recommend import get_xb
  14. from common.common import Common
  15. from common.db import MysqlHelper
  16. from common.feishu import Feishu
  17. from common.publish import Publish
  18. from common.public import random_title
  19. from common.userAgent import get_random_user_agent
  20. from common.public import get_user_from_mysql, get_config_from_mysql
  21. class DyFollow(object):
  22. platform = "抖音"
  23. tag = "抖音定向爬虫策略"
  24. @classmethod
  25. def get_rule(cls, log_type, crawler):
  26. try:
  27. while True:
  28. rule_sheet = Feishu.get_values_batch(log_type, crawler, "fn2hEO")
  29. if rule_sheet is None:
  30. Common.logger(log_type, crawler).warning("rule_sheet is None! 10秒后重新获取")
  31. time.sleep(10)
  32. continue
  33. rule_dict = {
  34. "video_width": int(rule_sheet[0][2]),
  35. "video_height": int(rule_sheet[1][2]),
  36. "like_cnt": int(rule_sheet[2][2]),
  37. "duration": int(rule_sheet[3][2]),
  38. "publish_time": int(rule_sheet[4][2]),
  39. }
  40. return rule_dict
  41. except Exception as e:
  42. Common.logger(log_type, crawler).error(f"get_rule:{e}\n")
  43. # 下载规则
  44. @classmethod
  45. def download_rule(cls, video_info_dict, rule_dict):
  46. # if video_info_dict['play_cnt'] >= rule_dict['play_cnt']:
  47. # if video_info_dict['comment_cnt'] >= rule_dict['comment_cnt']:
  48. if video_info_dict['like_cnt'] >= rule_dict['like_cnt']:
  49. if video_info_dict['duration'] >= rule_dict['duration']:
  50. if video_info_dict['video_width'] >= rule_dict['video_width'] \
  51. or video_info_dict['video_height'] >= rule_dict['video_height']:
  52. return True
  53. else:
  54. return False
  55. else:
  56. return False
  57. else:
  58. return False
  59. # else:
  60. # return False
  61. # else:
  62. # return False
  63. # 过滤词库
  64. @classmethod
  65. def filter_words(cls, log_type, crawler):
  66. try:
  67. while True:
  68. filter_words_sheet = Feishu.get_values_batch(log_type, crawler, '6BS2RR')
  69. if filter_words_sheet is None:
  70. Common.logger(log_type, crawler).warning(f"filter_words_sheet:{filter_words_sheet} 10秒钟后重试")
  71. continue
  72. filter_words_list = []
  73. for x in filter_words_sheet:
  74. for y in x:
  75. if y is None:
  76. pass
  77. else:
  78. filter_words_list.append(y)
  79. return filter_words_list
  80. except Exception as e:
  81. Common.logger(log_type, crawler).error(f'filter_words异常:{e}\n')
  82. @classmethod
  83. def video_title(cls, log_type, env, crawler, title):
  84. title_split1 = title.split(" #")
  85. if title_split1[0] != "":
  86. title1 = title_split1[0]
  87. else:
  88. title1 = title_split1[-1]
  89. title_split2 = title1.split(" #")
  90. if title_split2[0] != "":
  91. title2 = title_split2[0]
  92. else:
  93. title2 = title_split2[-1]
  94. title_split3 = title2.split("@")
  95. if title_split3[0] != "":
  96. title3 = title_split3[0]
  97. else:
  98. title3 = title_split3[-1]
  99. video_title = title3.strip().split('#')[0].replace("\n", "") \
  100. .replace("/", "").replace("抖音", "").replace(" ", "") \
  101. .replace(" ", "").replace("&NBSP", "").replace("\r", "") \
  102. .replace(".", "。").replace("\\", "") \
  103. .replace(":", "").replace("*", "").replace("?", "") \
  104. .replace("?", "").replace('"', "").replace("<", "") \
  105. .replace(">", "").replace("|", "").replace("@", "").replace('"', '').replace("'", '')[:40]
  106. if video_title.replace(" ", "") == "" or video_title == "。。。" or video_title == "...":
  107. return random_title(log_type, crawler, env, text='title')
  108. else:
  109. return video_title
  110. @classmethod
  111. def get_videoList(cls, log_type, crawler, strategy, our_uid, out_uid, oss_endpoint, env, machine, rule_dict):
  112. try:
  113. max_cursor = ''
  114. url = "https://www.douyin.com/aweme/v1/web/aweme/post/?device_platform=webapp&aid=6383&channel=channel_pc_web&sec_user_id={sec_user_id}&max_cursor={max_cursor}&show_live_replay_strategy=1&count=10&publish_video_strategy_type=2&pc_client_type=1&version_code=170400&version_name=17.4.0&cookie_enabled=true&screen_width=1440&screen_height=900&browser_language=zh-CN&browser_platform=MacIntel&browser_name=Chrome&browser_version=112.0.0.0&browser_online=true&engine_name=Blink&engine_version=112.0.0.0&os_name=Mac+OS&os_version=10.15.7&cpu_core_num=8&device_memory=8&platform=PC&downlink=10&effective_type=4g&round_trip_time=50".format(
  115. sec_user_id=out_uid, max_cursor=max_cursor)
  116. headers = {
  117. 'authority': 'www.douyin.com',
  118. 'accept': 'application/json, text/plain, */*',
  119. 'accept-language': 'zh-CN,zh;q=0.9',
  120. # 'cookie': '__ac_nonce=06437a18000f23ad954f0; __ac_signature=_02B4Z6wo00f01Sb71TAAAIDCsi2OPpjonN0m29GAAC2M85; s_v_web_id=verify_lgeqr3uq_3aDaqQXf_juHS_40Yi_BE8b_tI8FCILZQXPK; _tea_utm_cache_2018=undefined; ttwid=1%7Cq_IBs6hbBUOIEcRR1gxtgY6GiTbTE3U1XhJNLL_9BZA%7C1681367431%7Cf77b36ae4721884fec1c3fa9d6a08c29e308236ae13df58d1be3b0d1f82f8668; strategyABtestKey=%221681367433.454%22; passport_csrf_token=bff0289a5846e58b4b9db6e1f64665f4; passport_csrf_token_default=bff0289a5846e58b4b9db6e1f64665f4; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtY2xpZW50LWNzciI6Ii0tLS0tQkVHSU4gQ0VSVElGSUNBVEUgUkVRVUVTVC0tLS0tXHJcbk1JSUJEVENCdFFJQkFEQW5NUXN3Q1FZRFZRUUdFd0pEVGpFWU1CWUdBMVVFQXd3UFltUmZkR2xqYTJWMFgyZDFcclxuWVhKa01Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRVhzcHJ5TElFT3E4Z2tPc2l5MTdSS1dEcVxyXG5xTXZkWEt5Y1V5NStiL3JpSmJ6VkMwMlYrU1dNaWtZTlNOK29IU2g2WVVTTmdUUjJrZEhvRUxISmxGdU9scUFzXHJcbk1Db0dDU3FHU0liM0RRRUpEakVkTUJzd0dRWURWUjBSQkJJd0VJSU9kM2QzTG1SdmRYbHBiaTVqYjIwd0NnWUlcclxuS29aSXpqMEVBd0lEUndBd1JBSWdIeW9SblFNK0h0Z3ZOU2dFMVpHdGpmYWQxT3BuWHJRdVFSNXNSaDkwakRJQ1xyXG5JRG1tVkthRkN5djBLemtpZ0J0RExaTVJSNndURzRBWUVoNUlWUmlZUU9UVVxyXG4tLS0tLUVORCBDRVJUSUZJQ0FURSBSRVFVRVNULS0tLS1cclxuIn0=; msToken=ZPkeAqCnLbjDWCkWcWf36ZZIoZTl07X33ca0xcNGk3tZPoMvgx-lo28oNb5JhbCKsXLgLNIoojAbocBrjdAv54Hwf-Tk3_yAjLW7WJxxSa0=; ttcid=54b98e03a03e43e09211ee28db90fdd126; home_can_add_dy_2_desktop=%221%22; msToken=nqMSwn8xJAXLZk2AikdOeJ6P3JvoCsbYjHROoR55KXMDvWs8auYCMpZFGQSClHhitgB0l_vwg8m0-lE-aWQovfN7Ga1QupM3SpdNktiamFRiHMdJExREc9_uxS1ln8E=; tt_scid=DnO5GFg1oLONpPMFuFeL-OveKBn43mRynRVTvHsh1KUQm283ocN6JX6qPKDDrFHbfdf1; download_guide=%222%2F20230413%22; msToken=b9haS5RjLaFgqVDoGp5xSqc8B4kl-miQB5Nku0BSIvHVutKT81Nzk_pPb0wm7xYlAp_nz1gytQng5gYeIRNxcMgZJ_MB7lhejt_093miXlHtvqAaxL0FNg==',
  121. 'referer': 'https://www.douyin.com/user/{}?showTab=post'.format(out_uid),
  122. 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
  123. 'sec-ch-ua-mobile': '?0',
  124. 'sec-ch-ua-platform': '"macOS"',
  125. 'sec-fetch-dest': 'empty',
  126. 'sec-fetch-mode': 'cors',
  127. 'sec-fetch-site': 'same-origin',
  128. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
  129. }
  130. x_bogus = get_xb(url, headers['user-agent'])
  131. url = url + '&X-Bogus={}'.format(x_bogus)
  132. if not x_bogus:
  133. return
  134. res = requests.get(url=url, headers=headers, data={}, proxies=Common.tunnel_proxies(), timeout=10).json()
  135. aweme_list = res.get('aweme_list', [])
  136. except Exception as e:
  137. Common.logger(log_type, crawler).error(f"获取抖音作者:{out_uid},视频列表失败:{e}")
  138. return
  139. if not aweme_list:
  140. Common.logger(log_type, crawler).warning(f"抖音作者没有获取到更多数据")
  141. return
  142. for info in aweme_list:
  143. if info.get('is_ads'):
  144. continue
  145. publish_time = info.get('create_time')
  146. if not publish_time:
  147. continue
  148. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time))
  149. publish_day = int((int(time.time()) - publish_time) / (3600 * 24))
  150. video_title = cls.video_title(log_type, env, crawler, info['desc'])
  151. if not video_title:
  152. video_title = random_title(log_type, crawler, env, text='title')
  153. video_dict = {'video_title': video_title,
  154. 'video_id': info['aweme_id'],
  155. 'play_cnt': info['statistics']['play_count'],
  156. 'comment_cnt': info['statistics']['comment_count'],
  157. 'like_cnt': info['statistics']['digg_count'],
  158. 'share_cnt': info['statistics']['share_count'],
  159. 'video_width': info['video']['width'],
  160. 'video_height': info['video']['height'],
  161. 'duration': round(info['video']['duration'] / 1000),
  162. 'publish_time': publish_day,
  163. 'publish_time_stamp': publish_time * 1000,
  164. 'publish_time_str': publish_time_str,
  165. 'user_name': info['author']['nickname'],
  166. 'user_id': info['author_user_id'],
  167. 'user_sec_id': info['author']['sec_uid'],
  168. 'avatar_url': info['author']['avatar_thumb']['url_list'][0],
  169. 'cover_url': info['video']['origin_cover']['url_list'][0].replace('\u0026', '&'),
  170. 'video_url': info['video']['play_addr']['url_list'][0],
  171. 'session': f"douyin{int(time.time())}"
  172. }
  173. for k, v in video_dict.items():
  174. Common.logger(log_type, crawler).info(f"{k}:{v}")
  175. cls.download_publish(log_type=log_type,
  176. crawler=crawler,
  177. video_dict=video_dict,
  178. rule_dict=rule_dict,
  179. strategy=strategy,
  180. our_uid=our_uid,
  181. oss_endpoint=oss_endpoint,
  182. env=env,
  183. machine=machine)
  184. @classmethod
  185. def repeat_video(cls, log_type, crawler, video_id, env, machine):
  186. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_id}"; """
  187. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env, machine)
  188. return len(repeat_video)
  189. # 下载 / 上传
  190. @classmethod
  191. def download_publish(cls, log_type, crawler, strategy, video_dict, rule_dict, our_uid, oss_endpoint, env, machine):
  192. try:
  193. filter_words = get_config_from_mysql(log_type, crawler, env, text='filter')
  194. for filter_word in filter_words:
  195. if filter_word in video_dict['video_title']:
  196. Common.logger(log_type, crawler).info('标题已中过滤词:{}\n', video_dict['video_title'])
  197. return
  198. if cls.download_rule(video_dict, rule_dict) is False:
  199. Common.logger(log_type, crawler).info('不满足抓取规则\n')
  200. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env, machine) != 0:
  201. Common.logger(log_type, crawler).info('视频已下载\n')
  202. else:
  203. # 下载视频
  204. Common.download_method(log_type=log_type, crawler=crawler, text='video',
  205. title=video_dict['video_title'], url=video_dict['video_url'])
  206. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  207. if os.path.getsize(f"./{crawler}/videos/{md_title}/video.mp4") == 0:
  208. # 删除视频文件夹
  209. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  210. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  211. return
  212. # ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  213. # if ffmpeg_dict is None or ffmpeg_dict['size'] == 0:
  214. # Common.logger(log_type, crawler).warning(f"下载的视频无效,已删除\n")
  215. # # 删除视频文件夹
  216. # shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  217. # return
  218. # 下载封面
  219. Common.download_method(log_type=log_type, crawler=crawler, text='cover',
  220. title=video_dict['video_title'], url=video_dict['cover_url'])
  221. # 保存视频信息至txt
  222. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  223. # 上传视频
  224. Common.logger(log_type, crawler).info("开始上传视频...")
  225. our_video_id = Publish.upload_and_publish(log_type=log_type,
  226. crawler=crawler,
  227. strategy=strategy,
  228. our_uid=our_uid,
  229. env=env,
  230. oss_endpoint=oss_endpoint)
  231. if env == 'dev':
  232. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  233. else:
  234. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  235. Common.logger(log_type, crawler).info("视频上传完成")
  236. if our_video_id is None:
  237. # 删除视频文件夹
  238. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  239. return
  240. # 视频写入飞书
  241. upload_time = int(time.time())
  242. values = [[
  243. our_video_id,
  244. time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  245. strategy,
  246. str(video_dict['video_id']),
  247. video_dict['video_title'],
  248. our_video_link,
  249. # video_dict['gid'],
  250. video_dict['play_cnt'],
  251. video_dict['comment_cnt'],
  252. video_dict['like_cnt'],
  253. video_dict['share_cnt'],
  254. video_dict['duration'],
  255. str(video_dict['video_width']) + '*' + str(video_dict['video_height']),
  256. video_dict['publish_time_str'],
  257. video_dict['user_name'],
  258. video_dict['user_id'],
  259. video_dict['avatar_url'],
  260. video_dict['cover_url'],
  261. video_dict['video_url']
  262. ]]
  263. # time.sleep(1)
  264. Feishu.insert_columns(log_type, 'douyin', "qV9VC0", "ROWS", 1, 2)
  265. Feishu.update_values(log_type, 'douyin', "qV9VC0", "A2:Z2", values)
  266. Common.logger(log_type, crawler).info(f"视频已保存至云文档\n")
  267. # 视频信息保存数据库
  268. insert_sql = f""" insert into crawler_video(video_id,
  269. user_id,
  270. out_user_id,
  271. platform,
  272. strategy,
  273. out_video_id,
  274. video_title,
  275. cover_url,
  276. video_url,
  277. duration,
  278. publish_time,
  279. play_cnt,
  280. comment_cnt,
  281. like_cnt,
  282. share_cnt,
  283. crawler_rule,
  284. width,
  285. height)
  286. values({our_video_id},
  287. {our_uid},
  288. "{video_dict['user_id']}",
  289. "{cls.platform}",
  290. "{strategy}",
  291. "{video_dict['video_id']}",
  292. "{video_dict['video_title']}",
  293. "{video_dict['cover_url']}",
  294. "{video_dict['video_url']}",
  295. {int(video_dict['duration'])},
  296. "{video_dict['publish_time_str']}",
  297. {int(video_dict['play_cnt'])},
  298. {int(video_dict['comment_cnt'])},
  299. {int(video_dict['like_cnt'])},
  300. {int(video_dict['share_cnt'])},
  301. '{json.dumps(rule_dict)}',
  302. {int(video_dict['video_width'])},
  303. {int(video_dict['video_height'])}) """
  304. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  305. MysqlHelper.update_values(log_type, crawler, insert_sql, env, machine)
  306. Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
  307. except Exception as e:
  308. Common.logger(log_type, crawler).error(f'download_publish异常:{e}\n')
  309. @classmethod
  310. def get_follow_videos(cls, log_type, crawler, strategy, oss_endpoint, env, machine):
  311. user_list = get_user_from_mysql(log_type, crawler, crawler, env)
  312. rule_dict = cls.get_rule(log_type, crawler)
  313. for user in user_list:
  314. spider_link = user["link"]
  315. out_uid = spider_link
  316. user_name = user["nick_name"]
  317. our_uid = user["uid"]
  318. Common.logger(log_type, crawler).info(f"开始抓取 {user_name} 用户主页视频\n")
  319. cls.get_videoList(log_type=log_type,
  320. crawler=crawler,
  321. strategy=strategy,
  322. our_uid=our_uid,
  323. out_uid=out_uid,
  324. oss_endpoint=oss_endpoint,
  325. env=env,
  326. machine=machine,
  327. rule_dict=rule_dict,
  328. )
  329. if __name__ == '__main__':
  330. DyFollow.get_follow_videos('author', 'douyin', '定向抓取策略', 'outer', 'prod', 'aliyun')