source_qianlima.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import math
  4. import random
  5. import time
  6. import requests
  7. from db.RedisDB import RedisFilter
  8. from utils.config_parms import (
  9. account_pool,
  10. area_dict,
  11. city_dict,
  12. province_dict,
  13. channel_dict,
  14. REQUEST_DATA_MAP
  15. )
  16. from utils.databases import mongo_table
  17. from utils.log import logger
  18. from utils.sessions_521 import http_session_521
  19. from utils.tools import sha1, get_today_of_day
  20. '''
  21. https://search.vip.qianlima.com/index.html#?sortType=6&isSearchWord=1&tab_index=0
  22. 搜索-2.0
  23. 1 = 招标信息
  24. 2 = 中标信息
  25. 3 = 拟在建项目
  26. 4 = 审批项目
  27. '''
  28. qlm = mongo_table('qlm', 'data_merge')
  29. dedup = RedisFilter('redis://:k5ZJR5KV4q7DRZ92DQ@172.17.189.142:7361/2')
  30. session = requests.session()
  31. class AccountViolationRiskError(Exception):
  32. pass
  33. def send_wechat_warning(msg, send=True):
  34. markdown = f'千里马列表页采集异常,请相关同事注意。'
  35. markdown += f'\n>异常详情:<font color=\"warning\">**{msg}**</font>'
  36. if not send:
  37. logger.info(markdown)
  38. return
  39. url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=079193d8-1856-443e-9f6d-ecc5c883bf11'
  40. headers_ = {'Content-Type': 'application/json'}
  41. json_data = {'msgtype': 'markdown', 'markdown': {'content': markdown}}
  42. request_params = dict(headers=headers_, json=json_data, timeout=10)
  43. response = requests.post(url, **request_params)
  44. logger.info(response.json())
  45. def get_account(area):
  46. return next((p for p in account_pool if area in p['follow']), None)
  47. def disrupt_account_pool():
  48. results = []
  49. copy_account_pool = list(account_pool)
  50. while copy_account_pool:
  51. idx = random.randint(0, len(copy_account_pool) - 1)
  52. results.append(copy_account_pool.pop(idx))
  53. return results
  54. def request(url, data, account, retries=5):
  55. global session
  56. ip, _ = str(account['proxies']['http']).replace('socks5://', '').split(':')
  57. phone = account['phone']
  58. resp, msg = None, ''
  59. usages, usages_521 = 0, 1
  60. while usages < retries:
  61. request_params = {}
  62. proxies = account['proxies']
  63. request_params.setdefault('data', data)
  64. request_params.setdefault('headers', account['headers'])
  65. request_params.setdefault('cookies', account['cookies'])
  66. request_params.setdefault('proxies', proxies)
  67. request_params.setdefault('timeout', 60)
  68. try:
  69. resp = session.post(url, **request_params)
  70. if resp.status_code == 521:
  71. while usages_521 < retries:
  72. success, _, cookies = http_session_521(session,
  73. url,
  74. headers=account['headers'],
  75. cookies=account['cookies'],
  76. data=data,
  77. proxies=account['proxies'])
  78. if success:
  79. break
  80. msg = f'账号[{phone}]反爬破解失败,次数:{usages_521}'
  81. logger.warning(msg)
  82. time.sleep(1)
  83. usages_521 += 1
  84. usages += 1
  85. elif resp.status_code == 429:
  86. msg = f'账号[{phone}]访问频繁,图形验证,异常状态码:{resp.status_code}'
  87. logger.error(msg)
  88. logger.warning(resp.content.decode())
  89. break
  90. elif resp.status_code in [401, 403, 404]:
  91. msg = f'账号[{phone}]登录已失效或封停,,异常状态码:{resp.status_code}'
  92. logger.error(msg)
  93. break
  94. elif str(resp.status_code).startswith('4'):
  95. msg = f'公网代理IP[{ip}]被封禁,,异常状态码:{resp.status_code}'
  96. logger.error(msg)
  97. break
  98. else:
  99. break
  100. except requests.RequestException as e:
  101. if not isinstance(e, requests.ConnectTimeout):
  102. usages += 1
  103. msg = f'访问失败,原因:{e.__class__.__name__}'
  104. else:
  105. usages = retries
  106. msg = f'访问失败,原因:代理访问超时[{proxies["https"]}]'
  107. logger.error(msg)
  108. return resp, msg
  109. def downloader(begin_date, end_date, category, address, page, page_size, account):
  110. """
  111. :param str begin_date: 开始时间,格式:xxxx-xx-xxx
  112. :param str end_date: 结束时间,格式:xxxx-xx-xxx
  113. :param int category: 栏目编号
  114. :param int address: 地区编号
  115. :param int page: 页码
  116. :param int page_size: 单页数据条数
  117. :param dict account: 采集账号
  118. """
  119. url = 'https://search.vip.qianlima.com/rest/service/website/search/solr'
  120. data = REQUEST_DATA_MAP[category]
  121. data['newAreas'] = str(address) # 设置地区
  122. data['timeType'] = 4 # 自定义时间参数
  123. data['beginTime'] = begin_date
  124. data['endTime'] = end_date
  125. data['currentPage'] = page
  126. data['numPerPage'] = page_size
  127. data = json.dumps(data)
  128. # 请求资源响应自定义状态, 成功=success 失败=failure 停止=stop IP封停=disable等
  129. request_status = 'failure'
  130. response, err = request(url, data, account)
  131. if response is None:
  132. request_status = 'server_error'
  133. return request_status, err
  134. results = []
  135. row_count = 0
  136. if response.status_code == 200:
  137. resp_json = response.json()
  138. if resp_json['code'] == 200:
  139. row_count = resp_json['data']['rowCount']
  140. items = resp_json['data']['data']
  141. for item in items:
  142. cid = sha1(str(item['contentid']))
  143. if not dedup.get(item['contentid']):
  144. dedup.add(item['contentid'])
  145. if 'popTitle' in item:
  146. item['title'] = item['popTitle']
  147. else:
  148. item['title'] = item['showTitle']
  149. addr = str(item['areaName']).split('-')
  150. area_ = addr[0] if len(addr) > 0 else ''
  151. city_ = addr[1] if len(addr) > 1 else ''
  152. if '国土' in item.get('progName', ''):
  153. channel = item['progName']
  154. else:
  155. channel = (item['noticeSegmentTypeName'] or item['progName'])
  156. results.append({
  157. 'site': '千里马',
  158. 'channel': channel,
  159. 'area': area_,
  160. 'city': city_,
  161. 'title': item['title'],
  162. 'publishtime': item['updateTime'],
  163. 'href': item.get('url', '')
  164. })
  165. if len(results) > 0:
  166. qlm.insert_many(results, ordered=False)
  167. request_status = 'success'
  168. if len(items) < page_size or len(results) == 0:
  169. request_status = 'stop'
  170. else:
  171. '''
  172. {
  173. "code": 200520,
  174. "msg": "抱歉,您在单位时间内的搜索次数已达上限,请联系客服购买会员!咨询电话:400-688-2000",
  175. "data": null
  176. }
  177. '''
  178. err = resp_json['msg']
  179. logger.info(err)
  180. elif response.status_code in [401, 403, 404]:
  181. request_status = 'disable'
  182. elif response.status_code in [405]:
  183. request_status = 'method_not_allowed'
  184. elif response.status_code in [429]:
  185. request_status = 'captcha_required'
  186. elif str(response.status_code).startswith('4'):
  187. request_status = 'client_ip_disable'
  188. if request_status in ['stop', 'success']:
  189. if page == 1:
  190. logger.info(f'千里马 {begin_date} 网站发布 {row_count} 条数据')
  191. logger.info(f'入库 {len(results)} 条')
  192. return request_status, err
  193. def automatic_pagination(**kwargs):
  194. reason = '' # 采集失败时原因
  195. close_spider = False
  196. send_warning = False
  197. retry_times, max_retries = 0, 3
  198. pages = list(range(1, 101)) # 目前qlm仅支持查看前10000数据
  199. while len(pages) > 0:
  200. if close_spider:
  201. if send_warning:
  202. send_wechat_warning(reason)
  203. break
  204. if send_warning and retry_times > max_retries:
  205. send_wechat_warning(reason)
  206. break
  207. page = pages.pop(0)
  208. logger.info(f'下载第{page}页数据')
  209. while True:
  210. err, reason = downloader(page=page, **kwargs)
  211. if err in ['server_error', 'client_ip_disable', 'captcha_required']:
  212. close_spider = True
  213. send_warning = True
  214. elif err == 'failure':
  215. interval = math.log(random.randint(100, 2400), 2)
  216. logger.debug(f'等待{interval}s,异常重试...')
  217. time.sleep(interval)
  218. continue
  219. elif err == 'disable':
  220. logger.warning('账号被禁止访问')
  221. retry_times += 1
  222. send_warning = True
  223. elif err == 'method_not_allowed':
  224. logger.warning('服务器禁止使用当前 HTTP 方法的请求')
  225. retry_times += 1
  226. send_warning = True
  227. elif err == 'stop':
  228. time.sleep(math.log(random.randint(100, 2400), 2))
  229. close_spider = True
  230. else:
  231. time.sleep(math.log(random.randint(100, 2400), 2))
  232. break
  233. if send_warning:
  234. raise AccountViolationRiskError
  235. def core(date: str, category: int, address: int, account, page_size=20):
  236. try:
  237. automatic_pagination(
  238. begin_date=date,
  239. end_date=date,
  240. category=category,
  241. address=address,
  242. page_size=page_size, # 每页数据最大条数
  243. account=account
  244. )
  245. return True
  246. except AccountViolationRiskError:
  247. return False
  248. def spider(date, page_size=40):
  249. logger.info('+++ 采集开始 +++')
  250. dates = [date] if not isinstance(date, list) else date
  251. try:
  252. for date in dates:
  253. for category, category_name in channel_dict.items():
  254. for area, cities in area_dict.items():
  255. account = get_account(area)
  256. if not account:
  257. # raise ValueError('采集账号不能为空!')
  258. logger.warning('暂无可用采集账号与代理!')
  259. continue
  260. for city in cities:
  261. logger.info(' && '.join([
  262. date,
  263. category_name,
  264. province_dict[area],
  265. city_dict[city]
  266. ]))
  267. if len(cities) == 1:
  268. city = area # 千里马取消了直辖市的分区,直接采集省市区域
  269. yield core(date, category, city, account, page_size=page_size)
  270. except Exception as e:
  271. logger.error(e)
  272. except KeyboardInterrupt:
  273. pass
  274. finally:
  275. logger.info('+++ 采集结束 +++')
  276. def history(date_lst: list):
  277. for result in spider(date_lst):
  278. if not result:
  279. break
  280. def start():
  281. date = get_today_of_day(-1)
  282. for result in spider(date, page_size=100):
  283. if not result:
  284. break
  285. if __name__ == '__main__':
  286. start()