common.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 time
  14. import requests
  15. import ffmpeg
  16. import urllib3
  17. import subprocess
  18. proxies = {"http": None, "https": None}
  19. class Common:
  20. # 统一获取当前时间 <class 'datetime.datetime'> 2022-04-14 20:13:51.244472
  21. now = datetime.datetime.now()
  22. # 昨天 <class 'str'> 2022-04-13
  23. yesterday = (date.today() + timedelta(days=-1)).strftime("%Y/%m/%d")
  24. # 今天 <class 'datetime.date'> 2022-04-14
  25. today = date.today()
  26. # 明天 <class 'str'> 2022-04-15
  27. tomorrow = (date.today() + timedelta(days=1)).strftime("%Y/%m/%d")
  28. # 使用 logger 模块生成日志
  29. @staticmethod
  30. def logger(log_type, crawler):
  31. """
  32. 使用 logger 模块生成日志
  33. """
  34. # 日志路径
  35. log_dir = f"./{crawler}/logs/"
  36. log_path = os.getcwd() + os.sep + log_dir
  37. if not os.path.isdir(log_path):
  38. os.makedirs(log_path)
  39. # 日志文件名
  40. # log_name = time.strftime("%Y-%m-%d", time.localtime(time.time())) + f'-{crawler}-{log_type}.log'
  41. # log_name = datetime.datetime.now().strftime('%Y-%m-%d') + f'-{crawler}-{log_type}.log'
  42. log_name = datetime.datetime.now().strftime('%Y-%m-%d') + '-' + crawler + '-' + log_type + '.log'
  43. # log_name = str(date.today()) + f"-{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='00:00')
  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":
  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. # 删除 charles 缓存文件,只保留最近的两个文件
  128. @classmethod
  129. def del_charles_files(cls, log_type, crawler):
  130. # 目标文件夹下所有文件
  131. all_file = sorted(os.listdir(f"./{crawler}/{crawler}_chlsfiles/"))
  132. for file in all_file[0:-3]:
  133. os.remove(f"./{crawler}/{crawler}_chlsfiles/{file}")
  134. cls.logger(log_type, crawler).info("删除 charles 缓存文件成功\n")
  135. # 保存视频信息至 "./videos/{video_dict['video_title}/info.txt"
  136. @classmethod
  137. def save_video_info(cls, log_type, crawler, video_dict):
  138. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  139. save_dict = {
  140. "video_title": "video_title",
  141. "video_id": "video_id",
  142. "duration": 0,
  143. "play_cnt": 0,
  144. "comment_cnt": 0,
  145. "like_cnt": 0,
  146. "share_cnt": 0,
  147. "video_width": 1920,
  148. "video_height": 1080,
  149. "publish_time_stamp": 946656000, # 2000-01-01 00:00:00
  150. "user_name": "crawler",
  151. "avatar_url": "http://weapppiccdn.yishihui.com/resources/images/pic_normal.png",
  152. "video_url": "video_url",
  153. "cover_url": "cover_url",
  154. "session": f"session-{int(time.time())}",
  155. }
  156. for video_key, video_value in video_dict.items():
  157. for save_key, save_value in save_dict.items():
  158. if save_key == video_key:
  159. save_dict[save_key] = video_value
  160. with open(f"./{crawler}/videos/{md_title}/info.txt", "w", encoding="UTF-8") as f_w:
  161. f_w.write(str(video_dict['video_id']) + "\n" +
  162. str(video_dict['video_title']) + "\n" +
  163. str(video_dict['duration']) + "\n" +
  164. str(video_dict['play_cnt']) + "\n" +
  165. str(video_dict['comment_cnt']) + "\n" +
  166. str(video_dict['like_cnt']) + "\n" +
  167. str(video_dict['share_cnt']) + "\n" +
  168. f"{video_dict['video_width']}*{video_dict['video_height']}" + "\n" +
  169. str(video_dict['publish_time_stamp']) + "\n" +
  170. str(video_dict['user_name']) + "\n" +
  171. str(video_dict['avatar_url']) + "\n" +
  172. str(video_dict['video_url']) + "\n" +
  173. str(video_dict['cover_url']) + "\n" +
  174. str(video_dict['session']))
  175. Common.logger(log_type, crawler).info("==========视频信息已保存至info.txt==========")
  176. # 封装下载视频或封面的方法
  177. @classmethod
  178. def download_method(cls, log_type, crawler, text, title, url):
  179. """
  180. 下载封面:text == "cover" ; 下载视频:text == "video"
  181. 需要下载的视频标题:d_title
  182. 视频封面,或视频播放地址:d_url
  183. 下载保存路径:"./files/{d_title}/"
  184. """
  185. videos_dir = f"./{crawler}/videos/"
  186. if not os.path.exists(videos_dir):
  187. os.mkdir(videos_dir)
  188. # 首先创建一个保存该视频相关信息的文件夹
  189. md_title = md5(title.encode('utf8')).hexdigest()
  190. video_path = f"./{crawler}/videos/{md_title}/"
  191. if not os.path.exists(video_path):
  192. os.mkdir(video_path)
  193. # 下载视频
  194. if text == "video":
  195. # 需要下载的视频地址
  196. video_url = str(url).replace('http://', 'https://')
  197. # 视频名
  198. video_name = "video.mp4"
  199. for i in range(3):
  200. try:
  201. # 下载视频,最多重试三次
  202. urllib3.disable_warnings()
  203. # response = requests.get(video_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  204. response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
  205. with open(video_path + video_name, "wb") as f:
  206. for chunk in response.iter_content(chunk_size=10240):
  207. f.write(chunk)
  208. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  209. break
  210. except Exception as e:
  211. cls.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  212. time.sleep(1)
  213. # 下载音频
  214. elif text == "audio":
  215. # 需要下载的视频地址
  216. audio_url = str(url).replace('http://', 'https://')
  217. # 音频名
  218. audio_name = "audio.mp4"
  219. # 下载视频
  220. urllib3.disable_warnings()
  221. # response = requests.get(audio_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  222. response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
  223. try:
  224. with open(video_path + audio_name, "wb") as f:
  225. for chunk in response.iter_content(chunk_size=10240):
  226. f.write(chunk)
  227. cls.logger(log_type, crawler).info("==========音频下载完成==========")
  228. except Exception as e:
  229. cls.logger(log_type, crawler).error(f"音频下载失败:{e}\n")
  230. # 下载封面
  231. elif text == "cover":
  232. # 需要下载的封面地址
  233. cover_url = str(url)
  234. # 封面名
  235. cover_name = "image.jpg"
  236. # 下载封面
  237. urllib3.disable_warnings()
  238. # response = requests.get(cover_url, proxies=cls.tunnel_proxies(), verify=False)
  239. response = requests.get(cover_url, verify=False)
  240. try:
  241. with open(video_path + cover_name, "wb") as f:
  242. f.write(response.content)
  243. cls.logger(log_type, crawler).info("==========封面下载完成==========")
  244. except Exception as e:
  245. cls.logger(log_type, crawler).error(f"封面下载失败:{e}\n")
  246. # youtube 视频下载
  247. elif text == "youtube_video":
  248. # 需要下载的视频地址
  249. video_url = url
  250. # 视频名
  251. video_name = "video.mp4"
  252. try:
  253. 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}'
  254. Common.logger(log_type, crawler).info(f"download_cmd:{download_cmd}")
  255. os.system(download_cmd)
  256. # move_cmd = f"mv {video_name} {video_path}"
  257. # os.system(move_cmd)
  258. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  259. except Exception as e:
  260. Common.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  261. # 西瓜视频 / 音频下载
  262. elif text == "xigua_video":
  263. # 需要下载的视频地址
  264. video_url = str(url).replace('http://', 'https://')
  265. # 视频名
  266. video_name = "video1.mp4"
  267. # 下载视频
  268. urllib3.disable_warnings()
  269. # response = requests.get(video_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  270. response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
  271. try:
  272. with open(video_path + video_name, "wb") as f:
  273. for chunk in response.iter_content(chunk_size=10240):
  274. f.write(chunk)
  275. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  276. except Exception as e:
  277. cls.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  278. elif text == "xigua_audio":
  279. # 需要下载的视频地址
  280. audio_url = str(url).replace('http://', 'https://')
  281. # 音频名
  282. audio_name = "audio1.mp4"
  283. # 下载视频
  284. urllib3.disable_warnings()
  285. # response = requests.get(audio_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  286. response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
  287. try:
  288. with open(video_path + audio_name, "wb") as f:
  289. for chunk in response.iter_content(chunk_size=10240):
  290. f.write(chunk)
  291. cls.logger(log_type, crawler).info("==========音频下载完成==========")
  292. except Exception as e:
  293. cls.logger(log_type, crawler).error(f"音频下载失败:{e}\n")
  294. @classmethod
  295. def ffmpeg(cls, log_type, crawler, video_path):
  296. # Common.logger(log_type, crawler).info(f"video_path:{video_path}")
  297. video_title = video_path.replace(f"./{crawler}/videos/", "").replace("/video.mp4", "")
  298. # Common.logger(log_type, crawler).info(f"video_title:{video_title}")
  299. md_title = md5(video_title.encode('utf8')).hexdigest()
  300. video_path = f"./{crawler}/videos/{md_title}/video.mp4"
  301. # Common.logger(log_type, crawler).info(f"{video_path}")
  302. if os.path.getsize(video_path) == 0:
  303. Common.logger(log_type, crawler).info(f'video_size:{os.path.getsize(video_path)}')
  304. return
  305. probe = ffmpeg.probe(video_path)
  306. video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  307. if video_stream is None:
  308. Common.logger(log_type, crawler).info('No video Stream found!')
  309. return
  310. format1 = probe['format']
  311. size = int(int(format1['size']) / 1024 / 1024)
  312. width = int(video_stream['width'])
  313. height = int(video_stream['height'])
  314. duration = int(float(video_stream['duration']))
  315. ffmpeg_dict = {
  316. 'width': width,
  317. 'height': height,
  318. 'duration': duration,
  319. 'size': size
  320. }
  321. return ffmpeg_dict
  322. # 合并音视频
  323. @classmethod
  324. def video_compose(cls, log_type, crawler, video_dir):
  325. video_title = video_dir.replace(f"./{crawler}/videos/", "")
  326. md_title = md5(video_title.encode('utf8')).hexdigest()
  327. video_dir = f"./{crawler}/videos/{md_title}"
  328. try:
  329. video_path = f'{video_dir}/video1.mp4'
  330. audio_path = f'{video_dir}/audio1.mp4'
  331. out_path = f'{video_dir}/video.mp4'
  332. 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}'
  333. # print(cmd)
  334. subprocess.call(cmd, shell=True)
  335. for file in os.listdir(video_dir):
  336. if file.split('.mp4')[0] == 'video1' or file.split('.mp4')[0] == 'audio1':
  337. os.remove(f'{video_dir}/{file}')
  338. Common.logger(log_type, crawler).info('合成成功\n')
  339. except Exception as e:
  340. Common.logger(log_type, crawler).error(f'video_compose异常:{e}\n')
  341. # 快代理
  342. @classmethod
  343. def tunnel_proxies(cls):
  344. # 隧道域名:端口号
  345. tunnel = "q796.kdltps.com:15818"
  346. # 用户名密码方式
  347. username = "t17772369458618"
  348. password = "5zqcjkmy"
  349. tunnel_proxies = {
  350. "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel},
  351. "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel}
  352. }
  353. # 白名单方式(需提前设置白名单)
  354. # proxies = {
  355. # "http": "http://%(proxy)s/" % {"proxy": tunnel},
  356. # "https": "http://%(proxy)s/" % {"proxy": tunnel}
  357. # }
  358. # 要访问的目标网页
  359. # target_url = "https://www.kuaishou.com/profile/3xk9tkk6kkwkf7g"
  360. # target_url = "https://dev.kdlapi.com/testproxy"
  361. # # 使用隧道域名发送请求
  362. # response = requests.get(target_url, proxies=proxies)
  363. # print(response.text)
  364. return tunnel_proxies
  365. if __name__ == "__main__":
  366. pass