app.py 5.5 KB

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