我认为您可能需要使用selenium,因为该页面上的实际价格信息是动态加载的,这是一个每隔2 秒更新一次的示例:
import time
from bs4 import BeautifulSoup
from decimal import Decimal
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
BASE_URL = 'https://www.binance.com/en'
BITCOIN_HREF = '/en/trade/BTC_BUSD'
LAST_PRICE_COLUMN_CLASS = 'css-g80xfv'
WAIT_SECONDS = 2
def main():
driver = webdriver.Chrome(ChromeDriverManager().install())
for _ in range(5): # replace with `while True:` if you want to get updates "indefinitely"
driver.get(BASE_URL)
time.sleep(WAIT_SECONDS)
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
btc_a_tag = soup.find('a', href=BITCOIN_HREF)
btc_price_string = btc_a_tag.find('div', class_=LAST_PRICE_COLUMN_CLASS).text
btc_price_decimal = Decimal(btc_price_string.strip('$').replace(',', ''))
print(f"btc_price_string={btc_price_string}, btc_price_decimal={btc_price_decimal}")
driver.close()
if __name__ == '__main__':
main()
示例输出:
btc_price_string=$19,306.29, btc_price_decimal=19306.29
btc_price_string=$19,307.85, btc_price_decimal=19307.85
btc_price_string=$19,308.18, btc_price_decimal=19308.18
btc_price_string=$19,308.41, btc_price_decimal=19308.41
btc_price_string=$19,308.18, btc_price_decimal=19308.18