dmarket.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import time
  2. import requests
  3. import sqlite3
  4. from datetime import datetime
  5. def get_dmarket_data():
  6. """从DMarket API获取商品数据"""
  7. url = "https://api.dmarket.com/exchange/v1/market/items"
  8. headers = {
  9. "Accept": "application/json, text/plain, */*",
  10. "Language": "ZH",
  11. "Referer": "https://dmarket.com/",
  12. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
  13. "jkkat": "eafac24b",
  14. "payment-session-id": "3a1b1e5b-2a62-420b-8064-444495216e98"
  15. }
  16. params = {
  17. "side": "market",
  18. "orderBy": "updated",
  19. "orderDir": "desc",
  20. "priceFrom": 0,
  21. "priceTo": 0,
  22. "gameId": "a8db",
  23. "types": "dmarket",
  24. "limit": 100, # 每次获取100条,可根据需要调整
  25. "currency": "USD",
  26. "platform": "browser"
  27. }
  28. response = requests.get(url, headers=headers, params=params)
  29. return response.json()
  30. def save_to_database(data):
  31. """保存DMarket数据到数据库"""
  32. conn = sqlite3.connect('buff_prices.db')
  33. cursor = conn.cursor()
  34. current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  35. try:
  36. items = data.get('objects', [])
  37. count = 0
  38. updated_count = 0
  39. not_found_count = 0
  40. for item in items:
  41. # 从DMarket数据中获取商品名称和磨损
  42. item_name = item.get('extra', {}).get('name', '')
  43. exterior = item.get('extra', {}).get('exterior', '')
  44. if not item_name:
  45. continue
  46. # 构建market_hash_name格式
  47. if exterior:
  48. market_hash_name = f"{item_name} ({exterior.capitalize()})"
  49. else:
  50. market_hash_name = item_name
  51. print(market_hash_name)
  52. # 在products表中查找匹配的商品
  53. cursor.execute('SELECT id FROM products WHERE market_hash_name LIKE ?', ('%' + market_hash_name,))
  54. product = cursor.fetchone()
  55. if product:
  56. product_id = product[0]
  57. # DMarket的price.USD单位是美分,转换为美元
  58. price_usd = item.get('price', {}).get('USD', '')
  59. if price_usd:
  60. min_price = float(price_usd) / 100
  61. else:
  62. continue
  63. # 插入或更新DMarket平台价格
  64. cursor.execute('''
  65. INSERT INTO platform_prices (product_id, platform_code, min_price, recorded_at, currency)
  66. VALUES (?, ?, ?, ?, 'USD')
  67. ON CONFLICT(product_id, platform_code) DO UPDATE SET
  68. min_price = excluded.min_price,
  69. recorded_at = excluded.recorded_at
  70. ''', (product_id, 'dmarket', min_price, current_time))
  71. updated_count += 1
  72. else:
  73. not_found_count += 1
  74. count += 1
  75. conn.commit()
  76. print(f"处理了 {count} 条DMarket商品数据")
  77. print(f"成功更新 {updated_count} 条价格")
  78. print(f"未匹配到商品 {not_found_count} 条")
  79. except Exception as e:
  80. conn.rollback()
  81. print(f"保存数据出错: {e}")
  82. finally:
  83. conn.close()
  84. def main():
  85. while True:
  86. response_data = get_dmarket_data()
  87. if response_data and 'objects' in response_data:
  88. save_to_database(response_data)
  89. else:
  90. print("API返回数据异常")
  91. time.sleep(5)
  92. if __name__ == "__main__":
  93. main()