app.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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","page_size": 80, "page_num": page_num, "tab": "selling"}
  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. "Cookie": "NTES_YD_SESS=9Ko5g05jJPzL0nDaqrG7L0B9n7AiGVSy0Q4Rh7lAlP3Ll.DwlvG8Q0qiKkN_BGxhLcofy9IT_mEPLnlsRxJMcT2j2ZHJdIidq2YgzyU9uC._XmVDURPonklYKRXNyoZ68AzWP5XQjf7Bz1ouZKiPQ5hfZoAcTClcSb0NUg2ijt4Ce5EYAMxsLEvFAnPKKgSjKIdOtZSpSJpOcBu11Bh9Ccum0uxDMGYj9; S_INFO=1774149977|0|0&60##|18511117532; P_INFO=18511117532|1774149977|1|netease_buff|00&99|null&null&null#xiz&540100#10#0|&0||18511117532; remember_me=U1089937100|UUBCBtmtPIUdtQZz9YmlUBjQ28AfdV8m; session=1-5oyvnvmyB29IGHS6qhrIkkZEjN-Jy2mGZ6NU34Eh3UPf2017034644; csrf_token=IjY0Mzg5OTRhYmY5MTFmNGU2MzBjZDI0ZjAwZWQxYzQ1YTdmYjEyZmUi.ab9hYA.awg5FDUiey0d1h9yU_kdomsG6lo",
  23. "Accept-Encoding": "gzip, deflate, br",
  24. "Connection": "keep-alive"
  25. }
  26. response = requests.get(url, headers=headers, params=querystring)
  27. return response.json()
  28. def save_to_database(data):
  29. """保存数据到数据库"""
  30. conn = sqlite3.connect('buff_prices.db')
  31. cursor = conn.cursor()
  32. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  33. try:
  34. items = data.get('data', {}).get('items', [])
  35. count = 0
  36. inserted_count = 0
  37. updated_count = 0
  38. for item in items:
  39. # 获取稀有度
  40. rarity = None
  41. if 'goods_info' in item and 'info' in item['goods_info']:
  42. tags = item['goods_info']['info'].get('tags', {})
  43. if 'rarity' in tags:
  44. rarity = tags['rarity'].get('localized_name')
  45. # 获取类型
  46. item_type = None
  47. if 'goods_info' in item and 'info' in item['goods_info']:
  48. tags = item['goods_info']['info'].get('tags', {})
  49. if 'type' in tags:
  50. item_type = tags['type'].get('localized_name')
  51. # 获取图标
  52. icon_url = None
  53. if 'goods_info' in item:
  54. icon_url = item['goods_info'].get('icon_url')
  55. # 插入或更新商品信息
  56. cursor.execute('''
  57. INSERT INTO products (buff_id, name, market_hash_name, type, rarity, icon_url, updated_at)
  58. VALUES (?, ?, ?, ?, ?, ?, ?)
  59. ON CONFLICT(buff_id) DO UPDATE SET
  60. name = excluded.name,
  61. market_hash_name = excluded.market_hash_name,
  62. type = excluded.type,
  63. rarity = excluded.rarity,
  64. icon_url = excluded.icon_url,
  65. updated_at = excluded.updated_at
  66. ''', (
  67. item['id'],
  68. item['name'],
  69. item['market_hash_name'],
  70. item_type,
  71. rarity,
  72. icon_url,
  73. current_time
  74. ))
  75. # 判断是插入还是更新
  76. if cursor.rowcount == 1:
  77. inserted_count += 1
  78. else:
  79. updated_count += 1
  80. # 获取刚插入或更新的商品ID
  81. cursor.execute('SELECT id FROM products WHERE buff_id = ?', (item['id'],))
  82. product = cursor.fetchone()
  83. product_id = product[0]
  84. # 插入或更新Buff平台价格
  85. cursor.execute('''
  86. INSERT INTO platform_prices (product_id, platform_code, min_price, recorded_at)
  87. VALUES (?, ?, ?, ?)
  88. ON CONFLICT(product_id, platform_code) DO UPDATE SET
  89. min_price = excluded.min_price,
  90. recorded_at = excluded.recorded_at
  91. ''', (
  92. product_id,
  93. 'buff',
  94. item['sell_min_price'],
  95. current_time
  96. ))
  97. count += 1
  98. conn.commit()
  99. print(f"成功保存 {count} 条商品数据")
  100. print(f"其中: 新插入 {inserted_count} 条, 更新 {updated_count} 条")
  101. except Exception as e:
  102. conn.rollback()
  103. print(f"保存数据出错: {e}")
  104. finally:
  105. conn.close()
  106. def main():
  107. ind = 0
  108. while ind < 400:
  109. ind = ind + 1
  110. # 获取Buff数据
  111. print("正在获取Buff数据,页码:" + str(ind))
  112. response_data = get_buff_data(ind)
  113. if response_data.get('code') == 'OK':
  114. # 保存到数据库
  115. save_to_database(response_data)
  116. else:
  117. print(f"API返回错误: {response_data.get('msg')}")
  118. time.sleep(5)
  119. if __name__ == "__main__":
  120. main()