tools.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on 2024-04-09
  4. ---------
  5. @summary: 主题爬虫 工具类
  6. ---------
  7. @author: Lzz
  8. """
  9. import calendar
  10. import datetime
  11. import functools
  12. import hashlib
  13. import random
  14. import re
  15. import time
  16. from collections import namedtuple
  17. import bson
  18. import execjs
  19. import redis
  20. import requests
  21. from loguru import logger
  22. from pymongo import MongoClient
  23. from utils.clean_html import cleaner
  24. try:
  25. from pymongo.errors import DuplicateKeyError
  26. from hashlib import md5
  27. except ImportError as e:
  28. raise e
  29. SearchText = namedtuple('SearchText', ['total'])
  30. def nsssjss():
  31. ex_js = '''
  32. const jsdom = require("jsdom");
  33. const {JSDOM} = jsdom;
  34. const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
  35. window = dom.window;
  36. document = window.document;
  37. JSEncrypt = require('jsencrypt')
  38. function encryptByRSA(value) {
  39. var encrypt = new JSEncrypt;
  40. var RSAPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCS2TZDs5+orLYCL5SsJ54+bPCVs1ZQQwP2RoPkFQF2jcT0HnNNT8ZoQgJTrGwNi5QNTBDoHC4oJesAVYe6DoxXS9Nls8WbGE8ZNgOC5tVv1WVjyBw7k2x72C/qjPoyo/kO7TYl6Qnu4jqW/ImLoup/nsJppUznF0YgbyU/dFFNBQIDAQAB";
  41. encrypt.setPublicKey('-----BEGIN PUBLIC KEY-----' + RSAPublicKey + '-----END PUBLIC KEY-----')
  42. return encrypt.encrypt(value)
  43. }
  44. function get_njs(){
  45. nsssjss = encryptByRSA('/freecms' + '/rest/v1/notice/selectInfoMoreChannel.do' + '$$' + new Date().getTime())
  46. return nsssjss
  47. }
  48. '''
  49. ctx = execjs.compile(ex_js)
  50. njs = ctx.call('get_njs')
  51. return njs
  52. def get_QGIP():
  53. proxy = "http://6278CF0D:41D9C796172D@tun-vdpzuj.qg.net:15254"
  54. proxies = {
  55. "http": proxy,
  56. "https": proxy,
  57. }
  58. return proxies
  59. def get_proxy(scheme=None, default=None, socks5h=False):
  60. headers = {
  61. "Authorization": "Basic amlhbnl1MDAxOjEyM3F3ZSFB"
  62. }
  63. while True:
  64. proxy = requests.get("http://cc.spdata.jianyu360.com/crawl/proxy/socks5/fetch", headers=headers).json()
  65. # proxy = requests.get("http://39.106.157.58:1405/crawl/proxy/socks5/fetch", headers=headers).json()
  66. proxies = proxy.get("data")
  67. if proxies:
  68. break
  69. else:
  70. logger.warning("暂无代理...")
  71. time.sleep(3)
  72. if socks5h:
  73. proxyh = {
  74. "http": proxies.get("http").replace("socks5", "socks5h"),
  75. "https": proxies.get("http").replace("socks5", "socks5h")
  76. }
  77. proxies = proxyh
  78. logger.info(f"切换代理: {proxies}")
  79. if not scheme:
  80. return proxies
  81. else:
  82. return proxies.get(scheme, default)
  83. def Mongo_client():
  84. client = MongoClient("172.17.4.87", 27080)
  85. # client = MongoClient("172.20.45.130", 27017)
  86. return client
  87. def Redis_client():
  88. _pool = redis.ConnectionPool(
  89. host='172.17.162.28',
  90. port=7361,
  91. password='k5ZJR5KV4q7DRZ92DQ',
  92. db=1
  93. )
  94. # _pool = redis.ConnectionPool(
  95. # host='172.20.45.129',
  96. # password='jianyu@python',
  97. # port=3379,
  98. # db=1
  99. # )
  100. r = redis.Redis(connection_pool=_pool, decode_responses=True)
  101. return r
  102. def int2long(param: int):
  103. """int 转换成 long """
  104. return bson.int64.Int64(param)
  105. def get_current_date(date_format="%Y-%m-%d %H:%M:%S"):
  106. return datetime.datetime.now().strftime(date_format)
  107. def date_to_timestamp(date, time_format="%Y-%m-%d %H:%M:%S"):
  108. """
  109. @summary:
  110. ---------
  111. @param date:将"2011-09-28 10:00:00"时间格式转化为时间戳
  112. @param time_format:时间格式
  113. ---------
  114. @result: 返回时间戳
  115. """
  116. if ":" in date:
  117. timestamp = time.mktime(time.strptime(date, time_format))
  118. else:
  119. timestamp = time.mktime(time.strptime(date, "%Y-%m-%d"))
  120. return int(timestamp)
  121. def timestamp_to_date(timestamp, time_format="%Y-%m-%d %H:%M:%S"):
  122. """
  123. @summary:
  124. ---------
  125. @param timestamp: 将时间戳转化为日期
  126. @param time_format: 日期格式
  127. ---------
  128. @result: 返回日期
  129. """
  130. if timestamp is None:
  131. raise ValueError("timestamp is null")
  132. date = time.localtime(timestamp)
  133. return time.strftime(time_format, date)
  134. def get_sha1(*args):
  135. """
  136. @summary: 获取唯一的40位值, 用于获取唯一的id
  137. ---------
  138. @param *args: 参与联合去重的值
  139. ---------
  140. @result: ba4868b3f277c8e387b55d9e3d0be7c045cdd89e
  141. """
  142. sha1 = hashlib.sha1()
  143. for arg in args:
  144. sha1.update(str(arg).encode())
  145. return sha1.hexdigest() # 40位
  146. def get_sha256(*args):
  147. """
  148. @summary: 获取唯一的64位值, 用于获取唯一的id
  149. ---------
  150. @param *args: 参与联合去重的值
  151. ---------
  152. @result: 5580c91ea29bf5bd963f4c08dfcacd983566e44ecea1735102bc380576fd6f30
  153. """
  154. sha256 = hashlib.sha256()
  155. for arg in args:
  156. sha256.update(str(arg).encode())
  157. return sha256.hexdigest() # 64位
  158. def md5value(val):
  159. md5 = hashlib.md5()
  160. if isinstance(val, bytes):
  161. md5.update(str(val).encode("utf-8"))
  162. elif isinstance(val, str):
  163. md5.update(val.encode("utf-8"))
  164. return md5.hexdigest()
  165. def ensure_int64(n):
  166. """
  167. >>> ensure_int64(None)
  168. 0
  169. >>> ensure_float(False)
  170. 0
  171. >>> ensure_float(12)
  172. 12
  173. >>> ensure_float("72")
  174. 72
  175. """
  176. if not n:
  177. return bson.int64.Int64(0)
  178. return bson.int64.Int64(n)
  179. def get_today_of_day(day_offset=0):
  180. return str(datetime.date.today() + datetime.timedelta(days=day_offset))
  181. def get_current_timestamp():
  182. return int(time.time())
  183. def add_zero(n):
  184. return "%02d" % n
  185. def sup_zero(indate):
  186. deal = indate.split(' ')
  187. head = deal[0].split('-')
  188. tail = ""
  189. if len(deal) == 2:
  190. tail = " " + deal[1]
  191. year = int(head[0])
  192. month = int(head[1])
  193. day = int(head[2])
  194. fdate = datetime.datetime(year=year, month=month, day=day)
  195. formatted_date = fdate.strftime("%Y-%m-%d") + tail
  196. return formatted_date
  197. def get_days_of_month(year, month):
  198. """
  199. 返回天数
  200. """
  201. return calendar.monthrange(year, month)[1]
  202. def get_year_month_and_days(month_offset=0):
  203. """
  204. @summary:
  205. ---------
  206. @param month_offset: 月份偏移量
  207. ---------
  208. @result: ('2019', '04', '30')
  209. """
  210. today = datetime.datetime.now()
  211. year, month = today.year, today.month
  212. this_year = int(year)
  213. this_month = int(month)
  214. total_month = this_month + month_offset
  215. if month_offset >= 0:
  216. if total_month <= 12:
  217. days = str(get_days_of_month(this_year, total_month))
  218. total_month = add_zero(total_month)
  219. return (year, total_month, days)
  220. else:
  221. i = total_month // 12
  222. j = total_month % 12
  223. if j == 0:
  224. i -= 1
  225. j = 12
  226. this_year += i
  227. days = str(get_days_of_month(this_year, j))
  228. j = add_zero(j)
  229. return (str(this_year), str(j), days)
  230. else:
  231. if (total_month > 0) and (total_month < 12):
  232. days = str(get_days_of_month(this_year, total_month))
  233. total_month = add_zero(total_month)
  234. return (year, total_month, days)
  235. else:
  236. i = total_month // 12
  237. j = total_month % 12
  238. if j == 0:
  239. i -= 1
  240. j = 12
  241. this_year += i
  242. days = str(get_days_of_month(this_year, j))
  243. j = add_zero(j)
  244. return (str(this_year), str(j), days)
  245. def get_month(month_offset=0):
  246. """''
  247. 获取当前日期前后N月的日期
  248. if month_offset>0, 获取当前日期前N月的日期
  249. if month_offset<0, 获取当前日期后N月的日期
  250. date format = "YYYY-MM-DD"
  251. """
  252. today = datetime.datetime.now()
  253. day = add_zero(today.day)
  254. (y, m, d) = get_year_month_and_days(month_offset)
  255. arr = (y, m, d)
  256. if int(day) < int(d):
  257. arr = (y, m, day)
  258. return "-".join("%s" % i for i in arr)
  259. def extract_file_type(file_name="附件名", file_url="附件地址", file_type_list=None):
  260. """
  261. 抽取附件类型
  262. Args:
  263. file_name: 附件名
  264. file_url: 附件地址
  265. file_type_list: 其他附件后缀
  266. Returns: 附件类型
  267. """
  268. if file_type_list is None:
  269. file_type_list = []
  270. if file_name and file_url:
  271. file_name = file_name.strip()
  272. file_types = ['zip', 'docx', 'ftp', 'pdf', 'doc', 'rar', 'gzzb', 'hzzbs',
  273. 'jpg', 'png', 'zbid', 'xls', 'xlsx', 'swp', 'dwg']
  274. if file_type_list:
  275. ftp_list = list(map(lambda x: x.lower(), file_type_list))
  276. file_types.extend(ftp_list)
  277. file_type = file_url.split('?')[0].split('.')[-1].lower()
  278. if file_type not in file_types:
  279. file_type = file_url.split('?')[-1].split('.')[-1].lower()
  280. if file_type in file_types:
  281. return file_type
  282. else:
  283. for ftp in file_types:
  284. file_type = re.search(ftp, file_name) or re.search("\." + ftp, file_url)
  285. if file_type:
  286. return file_type.group(0).replace('.', '')
  287. else:
  288. return file_type
  289. return None
  290. def remove_htmldata(remove_info_list: list, html: str, response):
  291. """
  292. 过滤详情页无效数据
  293. Args:
  294. remove_info_list: 需删除内容的xpath或文本 -> list [xpath,re,str] eg:['<re>data:image/(.*?)"',]
  295. html: 待清洗文本
  296. response: 原文响应体
  297. Returns: 清洗后的文本
  298. """
  299. if html and remove_info_list:
  300. for extra_item in remove_info_list:
  301. if re.search('^//.*', extra_item):
  302. extra_html_list = response.xpath(extra_item).extract()
  303. for extra_html in extra_html_list:
  304. if extra_html:
  305. html = html.replace(extra_html, '')
  306. elif re.search('^<re>.*', extra_item):
  307. extra_item = extra_item.replace('<re>', '')
  308. extra_html_list = re.findall(f'{extra_item}', html, re.S | re.I | re.M)
  309. if extra_html_list:
  310. for exhtml in extra_html_list:
  311. html = html.replace(exhtml, '')
  312. else:
  313. extra_html = extra_item
  314. if extra_html:
  315. html = html.replace(extra_html, '')
  316. return html
  317. def text_search(content: str) -> SearchText:
  318. """
  319. 中文检索
  320. :param content: 文本
  321. :return: 中文数量
  322. """
  323. if not content:
  324. return SearchText(0)
  325. results = re.findall('[\u4e00-\u9fa5]', content, re.S)
  326. # 列表长度即是中文的字数
  327. return SearchText(len(results))
  328. def clean_title(title):
  329. '''清洗标题'''
  330. if title:
  331. rule_list = [
  332. '\(\d{1,20}\)',
  333. '\[[\u4e00-\u9fa5]{1,9}\]',
  334. '【[\u4e00-\u9fa5]{1,9}】',
  335. ]
  336. for rule in rule_list:
  337. title = re.sub(rule, '', title)
  338. return title
  339. def substitute(html_str, special=None, completely=False):
  340. """HTML 替换"""
  341. html_str = cleaner(html=html_str, special=special, completely=completely)
  342. return html_str
  343. def handle_publish_time(publishtime):
  344. '''处理发布时间'''
  345. try:
  346. time_str = get_current_date().split(' ')[-1]
  347. if ':' not in publishtime:
  348. publishtime = publishtime + ' ' + time_str
  349. else:
  350. if '00:00:00' in publishtime:
  351. publishtime = publishtime.split(' ')[0] + ' ' + time_str
  352. l_np_publishtime = int2long(date_to_timestamp(publishtime))
  353. publishtime, l_np_publishtime = handle_publish_time_overdue(publishtime, l_np_publishtime)
  354. return publishtime, l_np_publishtime
  355. except:
  356. raise EOFError("publishtime 格式错误!")
  357. def handle_publish_time_overdue(publishtime, l_np_publishtime):
  358. """处理超期发布时间"""
  359. if l_np_publishtime and l_np_publishtime > get_current_timestamp():
  360. logger.warning("发布时间大于当前时间,已设置当前时间为发布时间!")
  361. publishtime = get_current_date()
  362. l_np_publishtime = ensure_int64(date_to_timestamp(publishtime))
  363. return publishtime, l_np_publishtime
  364. def handle_page_html(item):
  365. '''检测正文'''
  366. title = item.get('title')
  367. publishtime = item.get('publishtime')
  368. href = item.get('href')
  369. if href == "#":
  370. href = item.get('competehref')
  371. contenthtml = item.get('contenthtml')
  372. detail = item.get('detail')
  373. if not contenthtml:
  374. logger.warning(f"页面源码不能为空!\n 发布地址:{href}\n 发布时间:{publishtime}\n 标题:{title}")
  375. raise ValueError("无效正文!")
  376. else:
  377. if text_search(detail).total == 0:
  378. logger.warning("无内容数据,数据不入保存服务!")
  379. item['sendflag'] = "true"
  380. def check_data_validity(item):
  381. '''检测基础字段是否完整'''
  382. title = item.get('title')
  383. publishtime = item.get('publishtime')
  384. href = item.get('href')
  385. if href == "#":
  386. href = item.get('competehref')
  387. if not title or not publishtime or not href:
  388. logger.error(f"基础数据不能为空!\n 发布地址:{href}\n 发布时间:{publishtime}\n 标题:{title}")
  389. raise ValueError("基础数据异常")
  390. _fields = {
  391. 'title', 'publishtime', 'spidercode', 'infoformat', 'site',
  392. 'channel', 'area', 'city', 'jsondata', 'district', 'href',
  393. 'is_mixed', 'comeintime', 's_title', 'l_np_publishtime',
  394. 'contenthtml', 'competehref', 'detail', 'iscompete', 'sendflag',
  395. '_d', 'publishdept', 'type', 'T', 'projectinfo', 'is_theme'
  396. }
  397. def clean_fields(item, special_fields=None):
  398. special_fields = special_fields or _fields
  399. rm_fields = []
  400. for key, val in item.items(): # 过滤非必须字段
  401. if key not in special_fields:
  402. rm_fields.append(key)
  403. for field in rm_fields:
  404. del item[field]
  405. def join_fields(item, special_fields=None, **kwargs):
  406. special_fields = special_fields or _fields
  407. for k, v in kwargs.items():
  408. if k in special_fields:
  409. item[k] = v
  410. else:
  411. logger.error(f"{k} 入库字段未定义!")
  412. def format_fields(item, callback=handle_publish_time, **kwargs):
  413. """ 格式化入库字段(bidding) """
  414. clean_fields(item)
  415. if callable(callback):
  416. time_str, timestamp = callback(item.get('publishtime'))
  417. item['publishtime'] = time_str
  418. item['l_np_publishtime'] = timestamp
  419. item['detail'] = substitute(item.get('contenthtml'))
  420. item['s_title'] = item.get('s_title') or item.get('title')
  421. item['infoformat'] = 1
  422. item['iscompete'] = True
  423. item['sendflag'] = 'false'
  424. item['_d'] = 'comeintime'
  425. item['publishdept'] = ''
  426. item['type'] = ''
  427. item['T'] = 'bidding'
  428. join_fields(item, **kwargs)
  429. handle_page_html(item)
  430. check_data_validity(item)
  431. item['comeintime'] = int2long(int(time.time()))
  432. return item
  433. def format_fields_njpc(item, callback=handle_publish_time, **kwargs):
  434. """ 格式化入库字段(拟建爬虫) """
  435. req_fields = {
  436. 'site', 'approvenumber', 'method', 'project_scale', 'area', 'is_mixed',
  437. 'competehref',
  438. 'air_conditioner', 'funds', 'scale', 'construction_area', 'channel',
  439. 'contenthtml', 'elevator',
  440. 'building_floors', 'ownertel', 'parking', 'building', 'spidercode',
  441. 'title',
  442. 'detail', 'projectinfo', 'exterior', 'constructionunit', 'owner_info',
  443. 'approvetime',
  444. 'project_startdate', 'investment', 'heating', 'district',
  445. 'constructionunitperson',
  446. 'designunitperson', 'publishtime', 'system', 'pace', 'total',
  447. 'project_scale_info', 'passive',
  448. 'phone', 'construction', 'parking_pace', 'floors', 'freshair_system',
  449. 'other_project_scale',
  450. 'conditioner', 'wall', 'designunit', 'owneraddr',
  451. 'prefabricated_building', 'materials',
  452. 'constructionunitaddr', 'constructionunit_info', 'project_person',
  453. 'approvecontent',
  454. 'constructionunittel', 'floor', 'person', 'city', 'floor_area',
  455. 'project', 'approvestatus',
  456. 'project_completedate', 'completedate', 'ownerperson', 'sendflag',
  457. 'comeintime',
  458. 'steel_structure', 'projectaddr', 'freshair', 'T', 'startdate', 'house',
  459. 'projectname',
  460. 'exterior_wall_materials', 'other', 'passive_house', 'jsondata', 'air',
  461. 'prefabricated',
  462. 'designunit_info', 'approvedept', 'total_investment', 'infoformat',
  463. 'project_phone',
  464. 'owner', 'designunittel', 'projecttype', 'approvecode', 'steel',
  465. 'is_theme', 'designunitaddr',
  466. 'heating_method', 'href', 'projectperiod', 'structure'
  467. }
  468. clean_fields(item, special_fields=req_fields)
  469. if callable(callback):
  470. _, timestamp = callback(item.get('publishtime'))
  471. item['publishtime'] = timestamp
  472. item['detail'] = substitute(item.get('contenthtml'))
  473. item['title'] = item.get('title') or item.get('projectname')
  474. item['infoformat'] = 2
  475. item['sendflag'] = "false"
  476. item['T'] = "bidding"
  477. join_fields(item, special_fields=req_fields, **kwargs)
  478. handle_page_html(item)
  479. check_data_validity(item)
  480. item['comeintime'] = int2long(int(time.time()))
  481. return item
  482. def search(pattern, string):
  483. result = re.search(pattern, string)
  484. if result:
  485. return result.groups()[0]
  486. def sleep_time(start_time: int, end_time=0, step=-1):
  487. time.sleep(random.random())
  488. for i in range(start_time, end_time, step):
  489. print(f"\r *** 休眠中... {i} 秒 *** ", end='')
  490. time.sleep(1)
  491. print("\r <* 休眠结束 *> ", end='')
  492. # 装饰器
  493. class Singleton(object):
  494. def __init__(self, cls):
  495. self._cls = cls
  496. self._instance = {}
  497. def __call__(self, *args, **kwargs):
  498. if self._cls not in self._instance:
  499. self._instance[self._cls] = self._cls(*args, **kwargs)
  500. return self._instance[self._cls]
  501. def down_load_image(proxy=None):
  502. img_url = 'https://gdgpo.czt.gd.gov.cn/freecms/verify/verifyCode.do?createTypeFlag=n'
  503. header = {
  504. "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
  505. "Accept-Language": "zh-CN,zh;q=0.9",
  506. "Connection": "keep-alive",
  507. "Referer": "https://gdgpo.czt.gd.gov.cn/cms-gd/site/guangdong/qwjsy/index.html?",
  508. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
  509. }
  510. res = requests.get(img_url, headers=header, proxies=proxy, timeout=30, verify=False)
  511. upload_address = "http://pycaptcha.spdata.jianyu360.com/v1/images/verify"
  512. content = {'file': res.content}
  513. # with open('image.jpg', 'wb+') as f:
  514. # f.write(res.content)
  515. headers = {'accept': 'application/json'}
  516. json_resp = requests.post(upload_address, headers=headers, files=content, stream=True).json()
  517. if "msg" in json_resp and "success" == json_resp["msg"]:
  518. code = json_resp["r"]["code"]
  519. if len(code) == 4:
  520. return code
  521. return None
  522. def _pack_file(file):
  523. """包装验证码格式"""
  524. if isinstance(file, str) and file.startswith("data:image"):
  525. img_file = {"file": file}
  526. elif isinstance(file, bytes):
  527. img_file = {"file": file}
  528. else:
  529. with open(file, "rb") as f:
  530. img_bytes = f.read()
  531. img_file = {"file": img_bytes}
  532. return img_file
  533. def simple_captcha(file):
  534. """
  535. 普通验证码
  536. @param file: 验证码 - 可以是图片或者图片base64编码
  537. @return:
  538. """
  539. url = "http://pycaptcha.spdata.jianyu360.com/v1/images/verify"
  540. files = _pack_file(file)
  541. r = requests.post(url, headers={"accept": "application/json"}, files=files, stream=True, timeout=10)
  542. rp_json = r.json()
  543. if "msg" in rp_json and "success" == rp_json["msg"]:
  544. return str(rp_json["r"]["code"])
  545. return None
  546. def retry_on_exception(retries=1, timeout=1):
  547. def decorate(func):
  548. @functools.wraps(func)
  549. def warp(*args, **kwargs):
  550. for _ in range(retries):
  551. try:
  552. return func(*args, **kwargs)
  553. except Exception as e:
  554. print(f"执行[{func.__name__}]失败, args:{args}, kwargs:{kwargs} 异常:{e}")
  555. time.sleep(timeout)
  556. raise RuntimeError(f"执行[{func.__name__}]达到最大重试次数")
  557. return warp
  558. return decorate
  559. class PySpiderError(Exception):
  560. def __init__(self, *args, **kwargs):
  561. if 'code' not in kwargs and 'reason' not in kwargs:
  562. kwargs['code'] = 10000
  563. kwargs['reason'] = '未知爬虫错误,请手动处理'
  564. for key, val in kwargs.items():
  565. setattr(self, key, val)
  566. super(PySpiderError, self).__init__(*args, kwargs)
  567. class AttachmentNullError(PySpiderError):
  568. def __init__(self, code: int = 10004, reason: str = '附件下载异常'):
  569. super(AttachmentNullError, self).__init__(code=code, reason=reason)
  570. class CustomError(Exception):
  571. def __init__(self, ErrorInfo):
  572. self.ErrorInfo = ErrorInfo
  573. def __str__(self):
  574. return self.ErrorInfo
  575. format_fileds = format_fields
  576. format_fileds_njpc = format_fields_njpc