hg3535_zq_status.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import jsonpath
  4. import scrapy
  5. import time
  6. from scrapy.http import Request
  7. import psycopg2
  8. import time
  9. # import datetime
  10. from functools import wraps
  11. from contextlib import contextmanager
  12. import psycopg2.extras
  13. from ..items import Zuqiustatus
  14. import json
  15. from datetime import datetime
  16. from datetime import date
  17. import itertools
  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. if not self.cursor:
  81. raise Warning("conn_error!")
  82. # 测试连接
  83. def test_conn(self):
  84. if self.cursor:
  85. print("conn success!")
  86. else:
  87. print('conn error!')
  88. # 单条语句的并提交
  89. def execute(self, sql_code):
  90. self.cursor.execute(sql_code)
  91. self.conn.commit()
  92. # 单条语句的不提交
  93. def execute_no_conmmit(self, sql_code):
  94. self.cursor.execute(sql_code)
  95. # 构造多条语句,使用%s参数化,对于每个list都进行替代构造
  96. def excute_many(self, sql_base, param_list):
  97. self.cursor.executemany(sql_base, param_list)
  98. # 批量执行(待完善)
  99. def batch_execute(self, sql_code):
  100. pass
  101. # 获取数据
  102. def get_data(self, sql_code, count=0):
  103. self.cursor.execute(sql_code)
  104. if int(count):
  105. return self.cursor.fetchmany(count)
  106. else:
  107. return self.cursor.fetchall()
  108. # 更新数据
  109. def updata_data(self, sql_code):
  110. self.cursor(sql_code)
  111. # 插入数据
  112. def insert_data(self, sql_code):
  113. self.cursor(sql_code)
  114. # 滚动游标
  115. def cursor_scroll(self, count, mode='relative'):
  116. self.cursor.scroll(count, mode=mode)
  117. # 提交
  118. def commit(self):
  119. self.conn.commit()
  120. # 回滚
  121. def rollback(self):
  122. self.conn.rollback()
  123. # 关闭连接
  124. def close_conn(self):
  125. self.cursor.close()
  126. self.conn.close()
  127. class ComplexEncoder(json.JSONEncoder):
  128. def default(self, obj):
  129. if isinstance(obj, datetime):
  130. return obj.strftime('%Y-%m-%d %H:%M:%S')
  131. elif isinstance(obj, date):
  132. return obj.strftime('%Y-%m-%d')
  133. else:
  134. return json.JSONEncoder.default(self, obj)
  135. class LanqiuSpider(scrapy.Spider):
  136. name = "ball_status"
  137. allowed_domains = ['hg3535z.com']
  138. to_day = datetime.now()
  139. #sid要改为1 足球 现在测试改为4
  140. start_urls = ['https://hg3535z.com/odds2/d/getodds?sid=1&pt=4&ubt=am&pn=0&sb=2&dc=null&pid=0'] # 滚球菜单 篮球滚球列url
  141. custom_settings = {
  142. "ITEM_PIPELINES": {
  143. 'hg3535.pipelines.BallStatuspipeline':200,
  144. },
  145. 'LOG_LEVEL': 'DEBUG',
  146. 'LOG_FILE': "../hg3535/log/ball_status_{}_{}_{}.log".format(to_day.year, to_day.month, to_day.day)
  147. }
  148. def parse(self, response):
  149. datas = json.loads(response.text)
  150. ids = jsonpath.jsonpath(datas, '$..i-ot[0]..egs..es..i[16]') # ids新列表
  151. item = Zuqiustatus()
  152. utime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  153. # zuqiu_total = {}
  154. zuqiu_status_list = []
  155. if ids:
  156. ids = set(ids)
  157. for i in ids:
  158. zuqiu = {}
  159. zuqiu['match_id'] = i
  160. zuqiu['create_time'] = utime
  161. zuqiu['status'] = 1
  162. zuqiu['ball_type'] = datas['i-ot'][0]['s']['n']
  163. zuqiu_status_list.append(zuqiu)
  164. item["zuqiu_total"] = zuqiu_status_list
  165. yield item