# -*- coding: utf-8 -*- import re import time import random from fastapi import FastAPI, HTTPException import uvicorn import httpx from fastapi.responses import HTMLResponse app = FastAPI() COIN_ITEMS = { 'btc': 'https://coinmarketcap.com/currencies/bitcoin/', 'eth': 'https://coinmarketcap.com/currencies/ethereum/', 'sol': 'https://coinmarketcap.com/currencies/solana/', 'sui': 'https://coinmarketcap.com/currencies/sui/', 'doge': 'https://coinmarketcap.com/currencies/dogecoin/', 'x': 'https://coinmarketcap.com/currencies/x-empire/', 'arb': 'https://coinmarketcap.com/currencies/arbitrum/', 'pepe': 'https://coinmarketcap.com/currencies/pepe/', 'grass': 'https://coinmarketcap.com/currencies/grass/', 'bome': 'https://coinmarketcap.com/currencies/book-of-meme/', } PROXIES = { "http://": "http://127.0.0.1:7890", "https://": "http://127.0.0.1:7890" } HEADERS = { "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" } @app.get("/coin/{proxy_type}/{coin_name}", response_class=HTMLResponse) async def read_coin(coin_name: str, proxy_type: int = 0): # -------------------------------------------------------------------------------- 所有url -------------------------------------------------------------------------------- if coin_name == 'all': try: result = get_all_coin_data(COIN_ITEMS, HEADERS, PROXIES, proxy_type) # 使用HTMLResponse返回居中的HTML内容 html_result = f"""
Request Error: {e}
", status_code=200) except Exception as e: return HTMLResponse(content=f"Internal Error: {e}
", status_code=200) else: # -------------------------------------------------------------------------------- 单个url -------------------------------------------------------------------------------- coin_url = COIN_ITEMS.get(coin_name) if not coin_url: return HTMLResponse(content=f"error: {coin_name}
", status_code=200) try: result = get_coin_data(coin_url, HEADERS, PROXIES, proxy_type) # 使用HTMLResponse返回居中的HTML内容 html_result = f"""Request Error: {e}
", status_code=200) except Exception as e: return HTMLResponse(content=f"Internal Error: {e}
", status_code=200) def get_coin_data(url: str, headers: dict, proxies: dict, proxy_type: int): result = '' if proxy_type: resp = httpx.get(url=url, headers=headers, proxies=proxies, timeout=3) else: resp = httpx.get(url=url, headers=headers, timeout=3) if resp.status_code != 200: raise HTTPException(status_code=resp.status_code,detail=f"Failed to retrieve data, status code: {resp.status_code}") page = resp.text text = re.search('(.*?)sc-65e7f566-0', page) if not text: return 'No Data' text = re.sub(r'', '', text.group(1)) text = re.sub(r'', '', text) text = re.sub(r'