hg3535_zq_status_up.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. # -*- coding: utf-8 -*-
  2. import jsonpath
  3. import scrapy
  4. from scrapy.http import Request
  5. import psycopg2
  6. import time
  7. from functools import wraps
  8. from contextlib import contextmanager
  9. import psycopg2.extras
  10. from scrapy.conf import settings
  11. import json
  12. from datetime import datetime
  13. from datetime import date
  14. import itertools
  15. import re
  16. from scrapy.xlib.pydispatch import dispatcher
  17. from scrapy import signals
  18. # 测试一个函数的运行时间,使用方式:在待测函数直接添加此修饰器
  19. def timethis(func):
  20. @wraps(func)
  21. def wrapper(*args, **kwargs):
  22. start = time.perf_counter()
  23. r = func(*args, **kwargs)
  24. end = time.perf_counter()
  25. print('\n============================================================')
  26. print('{}.{} : {}'.format(func.__module__, func.__name__, end - start))
  27. print('============================================================\n')
  28. return r
  29. return wrapper
  30. # 测试一段代码运行的时间,使用方式:上下文管理器with
  31. # with timeblock('block_name'):
  32. # your_code_block...
  33. @contextmanager
  34. def timeblock(label='Code'):
  35. start = time.perf_counter()
  36. try:
  37. yield
  38. finally:
  39. end = time.perf_counter()
  40. print('==============================================================')
  41. print('{} run time: {}'.format(label, end - start))
  42. print('==============================================================')
  43. class SqlConn():
  44. '''
  45. 连接数据库,以及进行一些操作的封装
  46. '''
  47. sql_name = ''
  48. database = ''
  49. user = ''
  50. password = ''
  51. port = 0
  52. host = ''
  53. # 创建连接、游标
  54. def __init__(self, *args, **kwargs):
  55. if kwargs.get("sql_name"):
  56. self.sql_name = kwargs.get("sql_name")
  57. if kwargs.get("database"):
  58. self.database = kwargs.get("database")
  59. if kwargs.get("user"):
  60. self.user = kwargs.get("user")
  61. if kwargs.get("password"):
  62. self.password = kwargs.get("password")
  63. if kwargs.get("port"):
  64. self.port = kwargs.get("port")
  65. if kwargs.get("host"):
  66. self.host = kwargs.get("host")
  67. if not (self.host and self.port and self.user and
  68. self.password and self.database):
  69. raise Warning("conn_error, missing some params!")
  70. sql_conn = {
  71. 'postgresql': psycopg2,
  72. }
  73. self.conn = sql_conn[self.sql_name].connect(host=self.host,
  74. port=self.port,
  75. user=self.user,
  76. password=self.password,
  77. database=self.database,
  78. )
  79. self.cursor = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
  80. # self.cursor = self.conn.cursor()
  81. if not self.cursor:
  82. raise Warning("conn_error!")
  83. # 测试连接
  84. def test_conn(self):
  85. if self.cursor:
  86. print("conn success!")
  87. else:
  88. print('conn error!')
  89. # 单条语句的并提交
  90. def execute(self, sql_code):
  91. self.cursor.execute(sql_code)
  92. self.conn.commit()
  93. # 单条语句的不提交
  94. def execute_no_conmmit(self, sql_code):
  95. self.cursor.execute(sql_code)
  96. # 构造多条语句,使用%s参数化,对于每个list都进行替代构造
  97. def excute_many(self, sql_base, param_list):
  98. self.cursor.executemany(sql_base, param_list)
  99. # 批量执行(待完善)
  100. def batch_execute(self, sql_code):
  101. pass
  102. # 获取数据
  103. def get_data(self, sql_code, count=0):
  104. self.cursor.execute(sql_code)
  105. if int(count):
  106. return self.cursor.fetchmany(count)
  107. else:
  108. return self.cursor.fetchall()
  109. # 更新数据
  110. def updata_data(self, sql_code):
  111. self.cursor.execute(sql_code)
  112. # 插入数据
  113. def insert_data(self, sql_code):
  114. self.cursor(sql_code)
  115. # 滚动游标
  116. def cursor_scroll(self, count, mode='relative'):
  117. self.cursor.scroll(count, mode=mode)
  118. # 提交
  119. def commit(self):
  120. self.conn.commit()
  121. # 回滚
  122. def rollback(self):
  123. self.conn.rollback()
  124. # 关闭连接
  125. def close_conn(self):
  126. self.cursor.close()
  127. self.conn.close()
  128. class ComplexEncoder(json.JSONEncoder):
  129. def default(self, obj):
  130. if isinstance(obj, datetime):
  131. return obj.strftime('%Y-%m-%d %H:%M:%S')
  132. elif isinstance(obj, date):
  133. return obj.strftime('%Y-%m-%d')
  134. else:
  135. return json.JSONEncoder.default(self, obj)
  136. class LanqiuSpider(scrapy.Spider):
  137. def __init__(self):
  138. super(LanqiuSpider).__init__()
  139. #信号量
  140. dispatcher.connect(self.spider_closed, signals.spider_closed)
  141. self.conn = SqlConn(sql_name='postgresql',host=settings["POST_HOST"], port=settings['POST_PORT'], user=settings["POST_USER"],password=settings["POST_PASSWORD"],database=settings["POST_DATABASE"])
  142. name = "ball_status_update"
  143. allowed_domains = ['hg3535z.com']
  144. #sid要改为1 足球 现在测试改为4
  145. start_urls = ['https://hg3535z.com/odds2/d/getodds?sid=3&pt=4&ubt=am&pn=0&sb=2&dc=null&pid=0'] # 滚球菜单 篮球滚球列url
  146. def parse(self, response):
  147. b = self.conn.get_data("select match_id from st_ball_status where ball_type='足球'")
  148. d = list(itertools.chain(*b))
  149. for i in d:
  150. urls = 'https://hg3535z.com/odds2/d/getamodds?eid={}&iip=true&ubt=am&isp=false'.format(i)
  151. yield Request(url=urls,callback=self.parse_each, dont_filter=True)
  152. #取得url中的id字段
  153. def re_str(self,url_str):
  154. a = (re.findall(r"eid=(.+?)&",url_str))
  155. result = "".join(a)
  156. return result
  157. def parse_each(self,response):
  158. if response.text != "null":
  159. res = json.loads(response.text)
  160. res1 = jsonpath.jsonpath(res,'$..eg..es[:]..o')
  161. if len(res1) > 1:
  162. print("这是有角球啊")
  163. o_dict0 = res1[0] # 递归取o字典
  164. o_dict1 = res1[1]
  165. re_url = response.request.url
  166. res_id = self.re_str(re_url)
  167. print("我是角球id是")
  168. print(res_id)
  169. if o_dict0 or o_dict1:
  170. print("这不是个空字典")
  171. print("我不做任何操作的啊")
  172. else:
  173. o_dict0 = res1[0]
  174. if not o_dict0:
  175. print("这是空字典我要改状态")
  176. re_url = response.request.url
  177. res_id = self.re_str(re_url)
  178. print(res_id)
  179. utime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  180. self.conn.updata_data("update st_ball_status set status=0, update_time='{0}' where match_id={1}".format(utime,res_id))
  181. self.conn.updata_data("update st_zq_result set status=2 where match_id={}".format(res_id))
  182. self.conn.updata_data("update st_zq_result_record set status=2 where match_id={}".format(res_id))
  183. self.conn.updata_data("update st_zq_competition set status=2 where match_id={}".format(res_id))
  184. self.conn.commit()
  185. if response.text == "null":
  186. print("暂时没有数据")
  187. re_url = response.request.url
  188. res_id = self.re_str(re_url)
  189. print(res_id)
  190. utime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  191. self.conn.updata_data("update st_ball_status set status=0, update_time='{0}' where match_id={1}".format(utime,res_id))
  192. sql1 = "insert into comendnotice(status, game_code, match_id,done_time) values (%s,%s, %s, %s) on conflict(match_id) do update set done_time = %s"
  193. self.conn.cursor.execute(sql1,(0,'zq',res_id,utime,utime))
  194. self.conn.updata_data("update st_zq_result set status=2 where match_id={}".format(res_id))
  195. self.conn.updata_data("update st_zq_result_record set status=2 where match_id={}".format(res_id))
  196. self.conn.updata_data("update st_zq_competition set status=2 where match_id={}".format(res_id))
  197. # cursor.execute(sql1, (match_id, create_time,staus,update_time, ball_type,update_time))
  198. self.conn.commit()
  199. def spider_closed(self, spider):
  200. print("我要关闭了")
  201. self.conn.close_conn()