message_coinmarketcap.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 使用 httpx 获取 coinmarketcap 最新数字币数据
  4. '''
  5. import httpx
  6. import re
  7. def get_coinmarketcap_coin_price(url, target):
  8. headers = {
  9. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107"
  10. }
  11. resp = httpx.get(url=url, headers=headers)
  12. if resp.status_code == 301:
  13. print(resp.text)
  14. exit(0)
  15. elif resp.status_code != 200:
  16. print(resp.status_code)
  17. exit(0)
  18. resp.encoding = 'utf-8'
  19. page = resp.text
  20. text = re.findall('<strong>(.*?)</p></div><div class="sc-65e7f566-0', page)[0] if re.findall(
  21. '<strong>(.*?)</p></div><div class="sc-65e7f566-0', page) else 'No Data'
  22. text = re.sub(r'</strong>', '', text)
  23. text = re.sub(r'<!-- -->', '', text)
  24. result = f'target: {target}\n'
  25. prices = re.findall(r'\$(\d+\.\d+)', text)
  26. if prices:
  27. result += f'prices: ${prices[0]}\n'
  28. volumes = re.findall(r'\$(\d{1,3}(?:,\d{3})*(?:\.\d+)?)', text)
  29. if volumes:
  30. result += f'24-hour trading volume: ${volumes[1]}\n'
  31. change = re.findall(r'(up|down) (\d+\.\d+)%', text)
  32. if change:
  33. c = ' '.join(change[0])
  34. result += f'change: {c}%\n'
  35. live_market_cap = re.findall(r'\$(\d{1,3}(?:,\d{3})*(?:\.\d+)?)', text)
  36. if live_market_cap:
  37. result += f'live market cap: ${live_market_cap[2]}\n'
  38. max_circulating_supply = re.findall(r'(\d{1,3}(?:,\d{3})*)', text)
  39. if max_circulating_supply:
  40. result += f'max circulating supply: {max_circulating_supply[-1]}'
  41. return result + '\n\n'
  42. if __name__ == '__main__':
  43. url_list = [
  44. # ['BTC', 'https://www.coinmarketcap.com/currencies/bitcoin/'],
  45. # ['ETH', 'https://www.coinmarketcap.com/currencies/ethereum/'],
  46. ['DOGE', 'https://coinmarketcap.com/currencies/dogecoin/'],
  47. ['ARB', 'https://coinmarketcap.com/currencies/arbitrum/'],
  48. ['ATH', 'https://coinmarketcap.com/currencies/aethir/'],
  49. ['SUI', 'https://coinmarketcap.com/currencies/sui/'],
  50. ]
  51. text = ''
  52. for data_list in url_list:
  53. text += get_coinmarketcap_coin_price(data_list[1], data_list[0])
  54. print(text)