Python 脚本使用 requests 库从 CoinGecko 等加密货币 API 获取当前 BTC(比特币)汇率:

import requests

def get_btc_rate():
    try:
        # URL for CoinGecko API to fetch BTC price
        url = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd'

        # Sending GET request to the API
        response = requests.get(url)

        # Checking if request was successful (status code 200)
        if response.status_code == 200:
            # Parsing JSON response
            data = response.json()

            # Extracting BTC price from response
            btc_price = data['bitcoin']['usd']

            return btc_price
        else:
            # If request fails, print error message
            print("Failed to fetch BTC rate. Status code:", response.status_code)
            return None
    except Exception as e:
        # Print any exceptions that occur during the process
        print("An error occurred:", str(e))
        return None

# Example usage:
btc_rate = get_btc_rate()
if btc_rate is not None:
    print("Current BTC rate: $", btc_rate)

该脚本向 CoinGecko API 发送 GET 请求,专门针对比特币兑美元的当前价格。然后,它解析 JSON 响应并提取 BTC 价格。最后,它打印当前 BTC 汇率。

在运行脚本之前,请确保您拥有 requests 已安装库(pip install requests)。此外,如果您频繁发出请求,请注意 API 使用限制。

以下是修改后的具有 SOCKS5 代理支持的脚本:

import requests

def get_btc_rate(proxy=None):
    try:
        # URL for CoinGecko API to fetch BTC price
        url = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd'

        # Defining proxy settings if provided
        proxies = {'http': proxy, 'https': proxy} if proxy else None

        # Sending GET request to the API with proxy settings
        response = requests.get(url, proxies=proxies)

        # Checking if request was successful (status code 200)
        if response.status_code == 200:
            # Parsing JSON response
            data = response.json()

            # Extracting BTC price from response
            btc_price = data['bitcoin']['usd']

            return btc_price
        else:
            # If request fails, print error message
            print("Failed to fetch BTC rate. Status code:", response.status_code)
            return None
    except Exception as e:
        # Print any exceptions that occur during the process
        print("An error occurred:", str(e))
        return None

# Example usage with SOCKS5 proxy
proxy_address = 'socks5://user:password@proxy_host:proxy_port'  # Replace with your SOCKS5 proxy details
btc_rate = get_btc_rate(proxy=proxy_address)
if btc_rate is not None:
    print("Current BTC rate: $", btc_rate)

更换 'user:password@proxy_host:proxy_port' SOCKS5 代理详细信息。如果您的 SOCKS5 代理不需要身份验证,则可以省略 user:password@ 部分。

评论 (0)

这里还没有评论,你可以成为第一个评论者!

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注


选择和购买代理

数据中心代理

轮流代理

UDP代理机构

受到全球 10000 多家客户的信赖

代理客户
代理客户
代理客户 flowch.ai
代理客户
代理客户
代理客户