source_qianlima.py 11 KB

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