common.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 = str(date.today()) + f"-{crawler}-{log_type}.log"
  42. # 日志不打印到控制台
  43. logger.remove(handler_id=None)
  44. # rotation="500 MB",实现每 500MB 存储一个文件
  45. # rotation="12:00",实现每天 12:00 创建一个文件
  46. # rotation="1 week",每周创建一个文件
  47. # retention="10 days",每隔10天之后就会清理旧的日志
  48. # 初始化日志
  49. logger.add(f"{log_dir}{log_name}", level="INFO", rotation='00:00')
  50. return logger
  51. # 写入阿里云日志
  52. @staticmethod
  53. def logging(log_type, crawler, env, message):
  54. """
  55. 写入阿里云日志
  56. 测试库: https://sls.console.aliyun.com/lognext/project/crawler-log-dev/logsearch/crawler-log-dev
  57. 正式库: https://sls.console.aliyun.com/lognext/project/crawler-log-prod/logsearch/crawler-log-prod
  58. :param log_type: 爬虫策略
  59. :param crawler: 哪款爬虫
  60. :param env: 环境
  61. :param message:日志内容
  62. :return: None
  63. """
  64. # 设置阿里云日志服务的访问信息
  65. accessKeyId = 'LTAIWYUujJAm7CbH'
  66. accessKey = 'RfSjdiWwED1sGFlsjXv0DlfTnZTG1P'
  67. if env == "dev":
  68. project = 'crawler-log-dev'
  69. logstore = 'crawler-log-dev'
  70. endpoint = 'cn-hangzhou.log.aliyuncs.com'
  71. else:
  72. project = 'crawler-log-prod'
  73. logstore = 'crawler-log-prod'
  74. endpoint = 'cn-hangzhou-intranet.log.aliyuncs.com'
  75. # 创建 LogClient 实例
  76. # print("创建 LogClient 实例")
  77. client = LogClient(endpoint, accessKeyId, accessKey)
  78. if '\r' in message:
  79. message = message.replace('\r', ' ')
  80. if '\n' in message:
  81. message = message.replace('\n', ' ')
  82. # print(f"message:{message}")
  83. log_group = []
  84. log_item = LogItem()
  85. # print(f"log_item:{type(log_item), log_item}")
  86. contents = [(f"{crawler}-{log_type}", message)]
  87. # print(f"contents:{type(contents), contents}")
  88. log_item.set_contents(contents)
  89. log_group.append(log_item)
  90. # print(f"log_group:{type(log_group), log_group}")
  91. # 写入日志
  92. # print("开始PutLogsRequest")
  93. request = PutLogsRequest(project=project,
  94. logstore=logstore,
  95. topic="",
  96. source="",
  97. logitems=log_group,
  98. compress=False)
  99. # print(f"request:{request}")
  100. # print("put_logs...")
  101. client.put_logs(request)
  102. # print("put_logs...done")
  103. # 清除日志,保留最近 10 个文件
  104. @classmethod
  105. def del_logs(cls, log_type, crawler):
  106. """
  107. 清除冗余日志文件
  108. :return: 保留最近 10 个日志
  109. """
  110. log_dir = f"./{crawler}/logs/"
  111. all_files = sorted(os.listdir(log_dir))
  112. all_logs = []
  113. for log in all_files:
  114. name = os.path.splitext(log)[-1]
  115. if name == ".log":
  116. all_logs.append(log)
  117. if len(all_logs) <= 30:
  118. pass
  119. else:
  120. for file in all_logs[:len(all_logs) - 30]:
  121. os.remove(log_dir + file)
  122. cls.logger(log_type, crawler).info("清除日志成功\n")
  123. # 删除 charles 缓存文件,只保留最近的两个文件
  124. @classmethod
  125. def del_charles_files(cls, log_type, crawler):
  126. # 目标文件夹下所有文件
  127. all_file = sorted(os.listdir(f"./{crawler}/{crawler}_chlsfiles/"))
  128. for file in all_file[0:-3]:
  129. os.remove(f"./{crawler}/{crawler}_chlsfiles/{file}")
  130. cls.logger(log_type, crawler).info("删除 charles 缓存文件成功\n")
  131. # 保存视频信息至 "./videos/{video_dict['video_title}/info.txt"
  132. @classmethod
  133. def save_video_info(cls, log_type, crawler, video_dict):
  134. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  135. save_dict = {
  136. "video_title": "video_title",
  137. "video_id": "video_id",
  138. "duration": 0,
  139. "play_cnt": 0,
  140. "comment_cnt": 0,
  141. "like_cnt": 0,
  142. "share_cnt": 0,
  143. "video_width": 1920,
  144. "video_height": 1080,
  145. "publish_time_stamp": 946656000, # 2000-01-01 00:00:00
  146. "user_name": "crawler",
  147. "avatar_url": "http://weapppiccdn.yishihui.com/resources/images/pic_normal.png",
  148. "video_url": "video_url",
  149. "cover_url": "cover_url",
  150. "session": f"session-{int(time.time())}",
  151. }
  152. for video_key, video_value in video_dict.items():
  153. for save_key, save_value in save_dict.items():
  154. if save_key == video_key:
  155. save_dict[save_key] = video_value
  156. with open(f"./{crawler}/videos/{md_title}/info.txt", "w", encoding="UTF-8") as f_w:
  157. f_w.write(str(video_dict['video_id']) + "\n" +
  158. str(video_dict['video_title']) + "\n" +
  159. str(video_dict['duration']) + "\n" +
  160. str(video_dict['play_cnt']) + "\n" +
  161. str(video_dict['comment_cnt']) + "\n" +
  162. str(video_dict['like_cnt']) + "\n" +
  163. str(video_dict['share_cnt']) + "\n" +
  164. f"{video_dict['video_width']}*{video_dict['video_height']}" + "\n" +
  165. str(video_dict['publish_time_stamp']) + "\n" +
  166. str(video_dict['user_name']) + "\n" +
  167. str(video_dict['avatar_url']) + "\n" +
  168. str(video_dict['video_url']) + "\n" +
  169. str(video_dict['cover_url']) + "\n" +
  170. str(video_dict['session']))
  171. Common.logger(log_type, crawler).info("==========视频信息已保存至info.txt==========")
  172. # 封装下载视频或封面的方法
  173. @classmethod
  174. def download_method(cls, log_type, crawler, text, title, url):
  175. """
  176. 下载封面:text == "cover" ; 下载视频:text == "video"
  177. 需要下载的视频标题:d_title
  178. 视频封面,或视频播放地址:d_url
  179. 下载保存路径:"./files/{d_title}/"
  180. """
  181. videos_dir = f"./{crawler}/videos/"
  182. if not os.path.exists(videos_dir):
  183. os.mkdir(videos_dir)
  184. # 首先创建一个保存该视频相关信息的文件夹
  185. md_title = md5(title.encode('utf8')).hexdigest()
  186. video_path = f"./{crawler}/videos/{md_title}/"
  187. if not os.path.exists(video_path):
  188. os.mkdir(video_path)
  189. # 下载视频
  190. if text == "video":
  191. # 需要下载的视频地址
  192. video_url = str(url).replace('http://', 'https://')
  193. # 视频名
  194. video_name = "video.mp4"
  195. for i in range(3):
  196. try:
  197. # 下载视频,最多重试三次
  198. urllib3.disable_warnings()
  199. # response = requests.get(video_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  200. response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
  201. with open(video_path + video_name, "wb") as f:
  202. for chunk in response.iter_content(chunk_size=10240):
  203. f.write(chunk)
  204. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  205. break
  206. except Exception as e:
  207. cls.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  208. time.sleep(1)
  209. # 下载音频
  210. elif text == "audio":
  211. # 需要下载的视频地址
  212. audio_url = str(url).replace('http://', 'https://')
  213. # 音频名
  214. audio_name = "audio.mp4"
  215. # 下载视频
  216. urllib3.disable_warnings()
  217. # response = requests.get(audio_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  218. response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
  219. try:
  220. with open(video_path + audio_name, "wb") as f:
  221. for chunk in response.iter_content(chunk_size=10240):
  222. f.write(chunk)
  223. cls.logger(log_type, crawler).info("==========音频下载完成==========")
  224. except Exception as e:
  225. cls.logger(log_type, crawler).error(f"音频下载失败:{e}\n")
  226. # 下载封面
  227. elif text == "cover":
  228. # 需要下载的封面地址
  229. cover_url = str(url)
  230. # 封面名
  231. cover_name = "image.jpg"
  232. # 下载封面
  233. urllib3.disable_warnings()
  234. # response = requests.get(cover_url, proxies=cls.tunnel_proxies(), verify=False)
  235. response = requests.get(cover_url, verify=False)
  236. try:
  237. with open(video_path + cover_name, "wb") as f:
  238. f.write(response.content)
  239. cls.logger(log_type, crawler).info("==========封面下载完成==========")
  240. except Exception as e:
  241. cls.logger(log_type, crawler).error(f"封面下载失败:{e}\n")
  242. # youtube 视频下载
  243. elif text == "youtube_video":
  244. # 需要下载的视频地址
  245. video_url = url
  246. # 视频名
  247. video_name = "video.mp4"
  248. try:
  249. 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}'
  250. Common.logger(log_type, crawler).info(f"download_cmd:{download_cmd}")
  251. os.system(download_cmd)
  252. # move_cmd = f"mv {video_name} {video_path}"
  253. # os.system(move_cmd)
  254. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  255. except Exception as e:
  256. Common.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  257. # 西瓜视频 / 音频下载
  258. elif text == "xigua_video":
  259. # 需要下载的视频地址
  260. video_url = str(url).replace('http://', 'https://')
  261. # 视频名
  262. video_name = "video1.mp4"
  263. # 下载视频
  264. urllib3.disable_warnings()
  265. # response = requests.get(video_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  266. response = requests.get(video_url, stream=True, proxies=proxies, verify=False)
  267. try:
  268. with open(video_path + video_name, "wb") as f:
  269. for chunk in response.iter_content(chunk_size=10240):
  270. f.write(chunk)
  271. cls.logger(log_type, crawler).info("==========视频下载完成==========")
  272. except Exception as e:
  273. cls.logger(log_type, crawler).error(f"视频下载失败:{e}\n")
  274. elif text == "xigua_audio":
  275. # 需要下载的视频地址
  276. audio_url = str(url).replace('http://', 'https://')
  277. # 音频名
  278. audio_name = "audio1.mp4"
  279. # 下载视频
  280. urllib3.disable_warnings()
  281. # response = requests.get(audio_url, stream=True, proxies=cls.tunnel_proxies(), verify=False)
  282. response = requests.get(audio_url, stream=True, proxies=proxies, verify=False)
  283. try:
  284. with open(video_path + audio_name, "wb") as f:
  285. for chunk in response.iter_content(chunk_size=10240):
  286. f.write(chunk)
  287. cls.logger(log_type, crawler).info("==========音频下载完成==========")
  288. except Exception as e:
  289. cls.logger(log_type, crawler).error(f"音频下载失败:{e}\n")
  290. @classmethod
  291. def ffmpeg(cls, log_type, crawler, video_path):
  292. # Common.logger(log_type, crawler).info(f"video_path:{video_path}")
  293. video_title = video_path.replace(f"./{crawler}/videos/", "").replace("/video.mp4", "")
  294. # Common.logger(log_type, crawler).info(f"video_title:{video_title}")
  295. md_title = md5(video_title.encode('utf8')).hexdigest()
  296. video_path = f"./{crawler}/videos/{md_title}/video.mp4"
  297. # Common.logger(log_type, crawler).info(f"{video_path}")
  298. if os.path.getsize(video_path) == 0:
  299. Common.logger(log_type, crawler).info(f'video_size:{os.path.getsize(video_path)}')
  300. return
  301. probe = ffmpeg.probe(video_path)
  302. video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  303. if video_stream is None:
  304. Common.logger(log_type, crawler).info('No video Stream found!')
  305. return
  306. format1 = probe['format']
  307. size = int(int(format1['size']) / 1024 / 1024)
  308. width = int(video_stream['width'])
  309. height = int(video_stream['height'])
  310. duration = int(float(video_stream['duration']))
  311. ffmpeg_dict = {
  312. 'width': width,
  313. 'height': height,
  314. 'duration': duration,
  315. 'size': size
  316. }
  317. return ffmpeg_dict
  318. # 合并音视频
  319. @classmethod
  320. def video_compose(cls, log_type, crawler, video_dir):
  321. video_title = video_dir.replace(f"./{crawler}/videos/", "")
  322. md_title = md5(video_title.encode('utf8')).hexdigest()
  323. video_dir = f"./{crawler}/videos/{md_title}"
  324. try:
  325. video_path = f'{video_dir}/video1.mp4'
  326. audio_path = f'{video_dir}/audio1.mp4'
  327. out_path = f'{video_dir}/video.mp4'
  328. 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}'
  329. # print(cmd)
  330. subprocess.call(cmd, shell=True)
  331. for file in os.listdir(video_dir):
  332. if file.split('.mp4')[0] == 'video1' or file.split('.mp4')[0] == 'audio1':
  333. os.remove(f'{video_dir}/{file}')
  334. Common.logger(log_type, crawler).info('合成成功\n')
  335. except Exception as e:
  336. Common.logger(log_type, crawler).error(f'video_compose异常:{e}\n')
  337. # 快代理
  338. @classmethod
  339. def tunnel_proxies(cls):
  340. # 隧道域名:端口号
  341. tunnel = "q796.kdltps.com:15818"
  342. # 用户名密码方式
  343. username = "t17772369458618"
  344. password = "5zqcjkmy"
  345. tunnel_proxies = {
  346. "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel},
  347. "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel}
  348. }
  349. # 白名单方式(需提前设置白名单)
  350. # proxies = {
  351. # "http": "http://%(proxy)s/" % {"proxy": tunnel},
  352. # "https": "http://%(proxy)s/" % {"proxy": tunnel}
  353. # }
  354. # 要访问的目标网页
  355. # target_url = "https://www.kuaishou.com/profile/3xk9tkk6kkwkf7g"
  356. # target_url = "https://dev.kdlapi.com/testproxy"
  357. # # 使用隧道域名发送请求
  358. # response = requests.get(target_url, proxies=proxies)
  359. # print(response.text)
  360. return tunnel_proxies
  361. if __name__ == "__main__":
  362. Common.tunnel_proxies()
  363. pass