Skrip Python menggunakan requests
perpustakaan untuk mengambil nilai BTC (Bitcoin) saat ini dari API cryptocurrency seperti CoinGecko:
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)
Skrip ini mengirimkan permintaan GET ke API CoinGecko, yang secara khusus menargetkan harga Bitcoin saat ini terhadap USD. Ini kemudian mem-parsing respons JSON dan mengekstrak harga BTC. Terakhir, ia mencetak nilai BTC saat ini.
Sebelum menjalankan skrip, pastikan Anda memiliki requests
perpustakaan diinstal (pip install requests
). Selain itu, perhatikan batas penggunaan API jika Anda sering membuat permintaan.
Berikut skrip yang dimodifikasi dengan dukungan proxy 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)
Mengganti 'user:password@proxy_host:proxy_port'
dengan detail proksi SOCKS5 Anda. Jika proksi SOCKS5 Anda tidak memerlukan autentikasi, Anda dapat menghilangkannya user:password@
bagian.
Komentar (0)
Belum ada komentar di sini, Anda bisa menjadi yang pertama!