common.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/1/31
  4. """
  5. 公共方法,包含:生成log / 删除log / 下载方法 / 删除 weixinzhishu_chlsfiles / 过滤词库 / 保存视频信息至本地 txt / 翻译 / ffmpeg
  6. """
  7. from aliyun.log import LogClient, PutLogsRequest, LogItem
  8. from datetime import date, timedelta
  9. from loguru import logger
  10. from hashlib import md5
  11. import datetime
  12. import os
  13. import json
  14. import time
  15. import requests
  16. import ffmpeg
  17. import urllib3
  18. import subprocess
  19. proxies = {"http": None, "https": None}
  20. class Common:
  21. # 统一获取当前时间 <class 'datetime.datetime'> 2022-04-14 20:13:51.244472
  22. now = datetime.datetime.now()
  23. # 昨天 <class 'str'> 2022-04-13
  24. yesterday = (date.today() + timedelta(days=-1)).strftime("%Y/%m/%d")
  25. # 今天 <class 'datetime.date'> 2022-04-14
  26. today = date.today()
  27. # 明天 <class 'str'> 2022-04-15
  28. tomorrow = (date.today() + timedelta(days=1)).strftime("%Y/%m/%d")
  29. # 使用 logger 模块生成日志
  30. @staticmethod
  31. def logger(log_type, crawler):
  32. """
  33. 使用 logger 模块生成日志
  34. """
  35. # 日志路径
  36. log_dir = f"./{crawler}/logs/"
  37. log_path = os.getcwd() + os.sep + log_dir
  38. if not os.path.isdir(log_path):
  39. os.makedirs(log_path)
  40. # 日志文件名
  41. # log_name = time.strftime("%Y-%m-%d", time.localtime(time.time())) + f'-{crawler}-{log_type}.log'
  42. # log_name = datetime.datetime.now().strftime('%Y-%m-%d') + f'-{crawler}-{log_type}.log'
  43. log_name = f"{date.today()}-{crawler}-{log_type}.log"
  44. # 日志不打印到控制台
  45. logger.remove(handler_id=None)
  46. # rotation="500 MB",实现每 500MB 存储一个文件
  47. # rotation="12:00",实现每天 12:00 创建一个文件
  48. # rotation="1 week",每周创建一个文件
  49. # retention="10 days",每隔10天之后就会清理旧的日志
  50. # 初始化日志
  51. logger.add(f"{log_dir}{log_name}", level="INFO", rotation=datetime.time(hour=0, minute=0), retention="10 days", enqueue=True)
  52. return logger
  53. # 写入阿里云日志
  54. @staticmethod
  55. def logging(log_type, crawler, env, message):
  56. """
  57. 写入阿里云日志
  58. 测试库: https://sls.console.aliyun.com/lognext/project/crawler-log-dev/logsearch/crawler-log-dev
  59. 正式库: https://sls.console.aliyun.com/lognext/project/crawler-log-prod/logsearch/crawler-log-prod
  60. :param log_type: 爬虫策略
  61. :param crawler: 哪款爬虫
  62. :param env: 环境
  63. :param message:日志内容
  64. :return: None
  65. """
  66. # 设置阿里云日志服务的访问信息
  67. accessKeyId = 'LTAIWYUujJAm7CbH'
  68. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  69. if env == "dev":
  70. project = 'crawler-log-dev'
  71. logstore = 'crawler-log-dev'
  72. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  73. elif crawler == "shipinhao" or crawler == "kanyikan":
  74. project = 'crawler-log-prod'
  75. logstore = 'crawler-log-prod'
  76. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  77. else:
  78. project = 'crawler-log-prod'
  79. logstore = 'crawler-log-prod'
  80. endpoint = 'cn-hangzhou-intranet.log.aliyuncs.com'
  81. # 创建 LogClient 实例
  82. client = LogClient(endpoint, accessKeyId, accessKey)
  83. if '\r' in message:
  84. message = message.replace('\r', ' ')
  85. if '\n' in message:
  86. message = message.replace('\n', ' ')
  87. log_group = []
  88. log_item = LogItem()
  89. """
  90. 生成日志消息体格式,例如
  91. crawler:xigua
  92. message:不满足抓取规则
  93. mode:search
  94. timestamp:1686656143
  95. """
  96. contents = [(f"crawler", str(crawler)), (f"mode", str(log_type)), (f"message", str(message)), ("timestamp", str(int(time.time())))]
  97. log_item.set_contents(contents)
  98. log_group.append(log_item)
  99. # 写入日志
  100. request = PutLogsRequest(project=project,
  101. logstore=logstore,
  102. topic="",
  103. source="",
  104. logitems=log_group,
  105. compress=False)
  106. client.put_logs(request)
  107. # 清除日志,保留最近 10 个文件
  108. @classmethod
  109. def del_logs(cls, log_type, crawler):
  110. """
  111. 清除冗余日志文件
  112. :return: 保留最近 10 个日志
  113. """
  114. log_dir = f"./{crawler}/logs/"
  115. all_files = sorted(os.listdir(log_dir))
  116. all_logs = []
  117. for log in all_files:
  118. name = os.path.splitext(log)[-1]
  119. if name == ".log":
  120. all_logs.append(log)
  121. if len(all_logs) <= 30:
  122. pass
  123. else:
  124. for file in all_logs[:len(all_logs) - 30]:
  125. os.remove(log_dir + file)
  126. cls.logger(log_type, crawler).info("清除日志成功\n")
  127. @classmethod
  128. def get_session(cls, log_type, crawler, env):
  129. while True:
  130. # charles 抓包文件保存目录
  131. charles_file_dir = f"./{crawler}/chlsfiles/"
  132. if int(len(os.listdir(charles_file_dir))) == 1:
  133. Common.logger(log_type, crawler).info("未找到chlsfile文件,等待60s")
  134. cls.logging(log_type, crawler, env, "未找到chlsfile文件,等待60s")
  135. time.sleep(60)
  136. continue
  137. # 目标文件夹下所有文件
  138. all_file = sorted(os.listdir(charles_file_dir))
  139. # 获取到目标文件
  140. old_file = all_file[-2]
  141. # 分离文件名与扩展名
  142. new_file = os.path.splitext(old_file)
  143. # 重命名文件后缀
  144. os.rename(os.path.join(charles_file_dir, old_file),
  145. os.path.join(charles_file_dir, new_file[0] + ".txt"))
  146. with open(charles_file_dir + new_file[0] + ".txt", encoding='utf-8-sig', errors='ignore') as f:
  147. contents = json.load(f, strict=False)
  148. if "search.weixin.qq.com" in [text['host'] for text in contents]:
  149. for text in contents:
  150. if text["host"] == "search.weixin.qq.com" \
  151. and text["path"] == "/cgi-bin/recwxa/recwxagetunreadmessagecnt":
  152. sessions = text["query"].split("session=")[-1].split("&wxaVersion=")[0]
  153. if "&vid" in sessions:
  154. session = sessions.split("&vid")[0]
  155. return session
  156. elif "&offset" in sessions:
  157. session = sessions.split("&offset")[0]
  158. return session
  159. elif "&wxaVersion" in sessions:
  160. session = sessions.split("&wxaVersion")[0]
  161. return session
  162. elif "&limit" in sessions:
  163. session = sessions.split("&limit")[0]
  164. return session
  165. elif "&scene" in sessions:
  166. session = sessions.split("&scene")[0]
  167. return session
  168. elif "&count" in sessions:
  169. session = sessions.split("&count")[0]
  170. return session
  171. elif "&channelid" in sessions:
  172. session = sessions.split("&channelid")[0]
  173. return session
  174. elif "&subscene" in sessions:
  175. session = sessions.split("&subscene")[0]
  176. return session
  177. elif "&clientVersion" in sessions:
  178. session = sessions.split("&clientVersion")[0]
  179. return session
  180. elif "&sharesearchid" in sessions:
  181. session = sessions.split("&sharesearchid")[0]
  182. return session
  183. elif "&nettype" in sessions:
  184. session = sessions.split("&nettype")[0]
  185. return session
  186. elif "&switchprofile" in sessions:
  187. session = sessions.split("&switchprofile")[0]
  188. return session
  189. elif "&switchnewuser" in sessions:
  190. session = sessions.split("&switchnewuser")[0]
  191. return session
  192. else:
  193. return sessions
  194. else:
  195. cls.logger(log_type, crawler).info("未找到 session,10s后重新获取")
  196. cls.logging(log_type, crawler, env, "未找到 session,10s后重新获取")
  197. time.sleep(10)
  198. # 删除 charles 缓存文件,只保留最近的两个文件
  199. @classmethod
  200. def del_charles_files(cls, log_type, crawler):
  201. # 目标文件夹下所有文件
  202. all_file = sorted(os.listdir(f"./{crawler}/chlsfiles/"))
  203. for file in all_file[0:-3]:
  204. os.remove(f"./{crawler}/chlsfiles/{file}")
  205. cls.logger(log_type, crawler).info("删除 charles 缓存文件成功\n")
  206. # 保存视频信息至 "./videos/{video_dict['video_title}/info.txt"
  207. @classmethod
  208. def save_video_info(cls, log_type, crawler, video_dict):
  209. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  210. save_dict = {
  211. "video_title": "video_title",
  212. "video_id": "video_id",
  213. "duration": 0,
  214. "play_cnt": 0,
  215. "comment_cnt": 0,
  216. "like_cnt": 0,
  217. "share_cnt": 0,
  218. "video_width": 1920,
  219. "video_height": 1080,
  220. "publish_time_stamp": 946656000, # 2000-01-01 00:00:00
  221. "user_name": "crawler",
  222. "avatar_url": "http://weapppiccdn.yishihui.com/resources/images/pic_normal.png",
  223. "video_url": "video_url",
  224. "cover_url": "cover_url",
  225. "session": f"session-{int(time.time())}",
  226. }
  227. for video_key, video_value in video_dict.items():
  228. for save_key, save_value in save_dict.items():
  229. if save_key == video_key:
  230. save_dict[save_key] = video_value
  231. with open(f"./{crawler}/videos/{md_title}/info.txt", "w", encoding="UTF-8") as f_w:
  232. f_w.write(str(video_dict['video_id']) + "\n" +
  233. str(video_dict['video_title']) + "\n" +
  234. str(video_dict['duration']) + "\n" +
  235. str(video_dict['play_cnt']) + "\n" +
  236. str(video_dict['comment_cnt']) + "\n" +
  237. str(video_dict['like_cnt']) + "\n" +
  238. str(video_dict['share_cnt']) + "\n" +
  239. f"{video_dict['video_width']}*{video_dict['video_height']}" + "\n" +
  240. str(video_dict['publish_time_stamp']) + "\n" +
  241. str(video_dict['user_name']) + "\n" +
  242. str(video_dict['avatar_url']) + "\n" +
  243. str(video_dict['video_url']) + "\n" +
  244. str(video_dict['cover_url']) + "\n" +
  245. str(video_dict['session']))
  246. Common.logger(log_type, crawler).info("==========视频信息已保存至info.txt==========")
  247. # 封装下载视频或封面的方法
  248. @classmethod
  249. def download_method(cls, log_type, crawler, text, title, url):
  250. """
  251. 下载封面:text == "cover" ; 下载视频:text == "video"
  252. 需要下载的视频标题:d_title
  253. 视频封面,或视频播放地址:d_url
  254. 下载保存路径:"./files/{d_title}/"
  255. """
  256. videos_dir = f"./{crawler}/videos/"
  257. if not os.path.exists(videos_dir):
  258. os.mkdir(videos_dir)
  259. # 首先创建一个保存该视频相关信息的文件夹
  260. md_title = md5(title.encode('utf8')).hexdigest()
  261. video_path = f"./{crawler}/videos/{md_title}/"
  262. if not os.path.exists(video_path):
  263. os.mkdir(video_path)
  264. # 下载视频
  265. if text == "video":
  266. # 需要下载的视频地址
  267. video_url = str(url).replace('http://', 'https://')
  268. # 视频名
  269. video_name = "video.mp4"
  270. for i in range(3):
  271. try:
  272. # 下载视频,最多重试三次
  273. urllib3.disable_warnings()
  274. # response = requests.get(video_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  275. response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
  276. with open(video_path + video_name, "wb") as f:
  277. for chunk in response.iter_content(chunk_size=10240):
  278. f.write(chunk)
  279. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  280. break
  281. except Exception as e:
  282. cls.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  283. time.sleep(1)
  284. # 下载音频
  285. elif text == "audio":
  286. # 需要下载的视频地址
  287. audio_url = str(url).replace('http://', 'https://')
  288. # 音频名
  289. audio_name = "audio.mp4"
  290. # 下载视频
  291. urllib3.disable_warnings()
  292. # response = requests.get(audio_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  293. response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
  294. try:
  295. with open(video_path + audio_name, "wb") as f:
  296. for chunk in response.iter_content(chunk_size=10240):
  297. f.write(chunk)
  298. cls.logger(log_type, crawler).info("==========音频下载完成==========")
  299. except Exception as e:
  300. cls.logger(log_type, crawler).error(f"音频下载失败:{e}\n")
  301. # 下载封面
  302. elif text == "cover":
  303. # 需要下载的封面地址
  304. cover_url = str(url)
  305. # 封面名
  306. cover_name = "image.jpg"
  307. # 下载封面
  308. urllib3.disable_warnings()
  309. # response = requests.get(cover_url, proxies=cls.tunnel_proxies(), verify=False)
  310. response = requests.get(cover_url, verify=False)
  311. try:
  312. with open(video_path + cover_name, "wb") as f:
  313. f.write(response.content)
  314. cls.logger(log_type, crawler).info("==========封面下载完成==========")
  315. except Exception as e:
  316. cls.logger(log_type, crawler).error(f"封面下载失败:{e}\n")
  317. # youtube 视频下载
  318. elif text == "youtube_video":
  319. # 需要下载的视频地址
  320. video_url = url
  321. # 视频名
  322. video_name = "video.mp4"
  323. try:
  324. download_cmd = f'yt-dlp -f "bv[height<=720][ext=mp4]+ba[ext=m4a]" --merge-output-format mp4 "{video_url}-U" -o {video_path}{video_name}'
  325. Common.logger(log_type, crawler).info(f"download_cmd:{download_cmd}")
  326. os.system(download_cmd)
  327. # move_cmd = f"mv {video_name} {video_path}"
  328. # os.system(move_cmd)
  329. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  330. except Exception as e:
  331. Common.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  332. # 西瓜视频 / 音频下载
  333. elif text == "xigua_video":
  334. # 需要下载的视频地址
  335. video_url = str(url).replace('http://', 'https://')
  336. # 视频名
  337. video_name = "video1.mp4"
  338. # 下载视频
  339. urllib3.disable_warnings()
  340. # response = requests.get(video_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  341. response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
  342. try:
  343. with open(video_path + video_name, "wb") as f:
  344. for chunk in response.iter_content(chunk_size=10240):
  345. f.write(chunk)
  346. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  347. except Exception as e:
  348. cls.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  349. elif text == "xigua_audio":
  350. # 需要下载的视频地址
  351. audio_url = str(url).replace('http://', 'https://')
  352. # 音频名
  353. audio_name = "audio1.mp4"
  354. # 下载视频
  355. urllib3.disable_warnings()
  356. # response = requests.get(audio_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  357. response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
  358. try:
  359. with open(video_path + audio_name, "wb") as f:
  360. for chunk in response.iter_content(chunk_size=10240):
  361. f.write(chunk)
  362. cls.logger(log_type, crawler).info("==========音频下载完成==========")
  363. except Exception as e:
  364. cls.logger(log_type, crawler).error(f"音频下载失败:{e}\n")
  365. @classmethod
  366. def ffmpeg(cls, log_type, crawler, video_path):
  367. # Common.logger(log_type, crawler).info(f"video_path:{video_path}")
  368. video_title = video_path.replace(f"./{crawler}/videos/", "").replace("/video.mp4", "")
  369. # Common.logger(log_type, crawler).info(f"video_title:{video_title}")
  370. md_title = md5(video_title.encode('utf8')).hexdigest()
  371. video_path = f"./{crawler}/videos/{md_title}/video.mp4"
  372. # Common.logger(log_type, crawler).info(f"{video_path}")
  373. if os.path.getsize(video_path) == 0:
  374. Common.logger(log_type, crawler).info(f'video_size:{os.path.getsize(video_path)}')
  375. return
  376. probe = ffmpeg.probe(video_path)
  377. video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  378. if video_stream is None:
  379. Common.logger(log_type, crawler).info('No video Stream found!')
  380. return
  381. format1 = probe['format']
  382. size = int(int(format1['size']) / 1024 / 1024)
  383. width = int(video_stream['width'])
  384. height = int(video_stream['height'])
  385. duration = int(float(video_stream['duration']))
  386. ffmpeg_dict = {
  387. 'width': width,
  388. 'height': height,
  389. 'duration': duration,
  390. 'size': size
  391. }
  392. return ffmpeg_dict
  393. # 合并音视频
  394. @classmethod
  395. def video_compose(cls, log_type, crawler, video_dir):
  396. video_title = video_dir.replace(f"./{crawler}/videos/", "")
  397. md_title = md5(video_title.encode('utf8')).hexdigest()
  398. video_dir = f"./{crawler}/videos/{md_title}"
  399. try:
  400. video_path = f'{video_dir}/video1.mp4'
  401. audio_path = f'{video_dir}/audio1.mp4'
  402. out_path = f'{video_dir}/video.mp4'
  403. cmd = f'ffmpeg -i {video_path} -i {audio_path} -c:v copy -c:a aac -strict experimental -map 0:v:0 -map 1:a:0 {out_path}'
  404. # print(cmd)
  405. subprocess.call(cmd, shell=True)
  406. for file in os.listdir(video_dir):
  407. if file.split('.mp4')[0] == 'video1' or file.split('.mp4')[0] == 'audio1':
  408. os.remove(f'{video_dir}/{file}')
  409. Common.logger(log_type, crawler).info('合成成功\n')
  410. except Exception as e:
  411. Common.logger(log_type, crawler).error(f'video_compose异常:{e}\n')
  412. # 快代理
  413. @classmethod
  414. def tunnel_proxies(cls):
  415. # 隧道域名:端口号
  416. tunnel = "q796.kdltps.com:15818"
  417. # 用户名密码方式
  418. username = "t17772369458618"
  419. password = "5zqcjkmy"
  420. tunnel_proxies = {
  421. "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel},
  422. "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel}
  423. }
  424. # 白名单方式(需提前设置白名单)
  425. # proxies = {
  426. # "http": "http://%(proxy)s/" % {"proxy": tunnel},
  427. # "https": "http://%(proxy)s/" % {"proxy": tunnel}
  428. # }
  429. # 要访问的目标网页
  430. # target_url = "https://www.kuaishou.com/profile/3xk9tkk6kkwkf7g"
  431. # target_url = "https://dev.kdlapi.com/testproxy"
  432. # # 使用隧道域名发送请求
  433. # response = requests.get(target_url, proxies=proxies)
  434. # print(response.text)
  435. return tunnel_proxies
  436. if __name__ == "__main__":
  437. print(datetime.time(hour=0, minute=0))
  438. pass