tools.py 21 KB

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