app.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import time
  2. import requests
  3. import sqlite3
  4. from datetime import datetime
  5. def get_buff_data(page_num):
  6. """从Buff API获取商品数据"""
  7. url = "https://buff.163.com/api/market/goods"
  8. querystring = {"game": "csgo"}
  9. headers = {
  10. "accept": "application/json, text/javascript, */*; q=0.01",
  11. "accept-language": "zh-CN,zh;q=0.9",
  12. "cache-control": "no-cache",
  13. "dnt": "1",
  14. "pragma": "no-cache",
  15. "priority": "u=1, i",
  16. "referer": "https://buff.163.com/market/csgo",
  17. "sec-fetch-dest": "empty",
  18. "sec-fetch-mode": "cors",
  19. "sec-fetch-site": "same-origin",
  20. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
  21. "x-requested-with": "XMLHttpRequest",
  22. "Accept-Encoding": "gzip, deflate, br",
  23. "Connection": "keep-alive"
  24. }
  25. proxies={
  26. "http": "socks5://USER660348-zone-custom-region-HK:e8b389@hk.rotgb.711proxy.com:10000",
  27. "https": "socks5://USER660348-zone-custom-region-HK:e8b389@hk.rotgb.711proxy.com:10000",
  28. }
  29. try:
  30. response = requests.get(url, headers=headers, params=querystring, proxies = proxies)
  31. return response.json()
  32. except Exception as e:
  33. print(f"请求出错: {e}")
  34. return None
  35. def save_to_database(data):
  36. """保存数据到数据库"""
  37. if data is None:
  38. print("数据为空,跳过保存")
  39. return
  40. conn = sqlite3.connect('buff_prices.db')
  41. cursor = conn.cursor()
  42. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  43. try:
  44. items = data.get('data', {}).get('items', [])
  45. count = 0
  46. inserted_count = 0
  47. updated_count = 0
  48. for item in items:
  49. # 获取稀有度
  50. rarity = None
  51. if 'goods_info' in item and 'info' in item['goods_info']:
  52. tags = item['goods_info']['info'].get('tags', {})
  53. if 'rarity' in tags:
  54. rarity = tags['rarity'].get('localized_name')
  55. # 获取类型
  56. item_type = None
  57. if 'goods_info' in item and 'info' in item['goods_info']:
  58. tags = item['goods_info']['info'].get('tags', {})
  59. if 'type' in tags:
  60. item_type = tags['type'].get('localized_name')
  61. # 获取图标
  62. icon_url = None
  63. if 'goods_info' in item:
  64. icon_url = item['goods_info'].get('icon_url')
  65. # 插入或更新商品信息
  66. cursor.execute('''
  67. INSERT INTO products (buff_id, name, market_hash_name, type, rarity, icon_url, updated_at)
  68. VALUES (?, ?, ?, ?, ?, ?, ?)
  69. ON CONFLICT(buff_id) DO UPDATE SET
  70. name = excluded.name,
  71. market_hash_name = excluded.market_hash_name,
  72. type = excluded.type,
  73. rarity = excluded.rarity,
  74. icon_url = excluded.icon_url,
  75. updated_at = excluded.updated_at
  76. ''', (
  77. item['id'],
  78. item['name'],
  79. item['market_hash_name'],
  80. item_type,
  81. rarity,
  82. icon_url,
  83. current_time
  84. ))
  85. # 判断是插入还是更新
  86. if cursor.rowcount == 1:
  87. inserted_count += 1
  88. else:
  89. updated_count += 1
  90. # 获取刚插入或更新的商品ID
  91. cursor.execute('SELECT id FROM products WHERE buff_id = ?', (item['id'],))
  92. product = cursor.fetchone()
  93. product_id = product[0]
  94. # 插入或更新Buff平台价格
  95. cursor.execute('''
  96. INSERT INTO platform_prices (product_id, platform_code, min_price, recorded_at)
  97. VALUES (?, ?, ?, ?)
  98. ON CONFLICT(product_id, platform_code) DO UPDATE SET
  99. min_price = excluded.min_price,
  100. recorded_at = excluded.recorded_at
  101. ''', (
  102. product_id,
  103. 'buff',
  104. item['sell_min_price'],
  105. current_time
  106. ))
  107. count += 1
  108. conn.commit()
  109. print(f"成功保存 {count} 条商品数据")
  110. print(f"其中: 新插入 {inserted_count} 条, 更新 {updated_count} 条")
  111. except Exception as e:
  112. conn.rollback()
  113. print(f"保存数据出错: {e}")
  114. finally:
  115. conn.close()
  116. def main():
  117. ind = 0
  118. while True:
  119. try:
  120. # ind = ind + 1
  121. # 获取Buff数据
  122. # print("正在获取Buff数据,页码:" + str(ind))
  123. response_data = get_buff_data(ind)
  124. if response_data and response_data.get('code') == 'OK':
  125. # 保存到数据库
  126. save_to_database(response_data)
  127. else:
  128. if response_data:
  129. print(f"API返回错误: {response_data.get('msg')}")
  130. else:
  131. print("获取数据失败")
  132. except Exception as e:
  133. print(f"主循环出错: {e}")
  134. time.sleep(30)
  135. if __name__ == "__main__":
  136. main()