从交易所网页获取最新价格

I am self-learning on python and currently trying to get a crypto recent price from Binance (https://www.binance.com/en/trade/LTC_USDT). the Html of the price is shown in the following figure:image

the Html code shown in the image above is located here on the website:code location

正如您所看到的那样,Html代码中的两个地方都提到了LTC的价格(当前约为43美元)。

第一个位置的类地址根据价格变化根据文本颜色在3个地址之间变化,如下所示:

红色文字(价格下降)>>>>> class =“ sc-1p4en3j-3 sc-1p4en3j-5 jFILqo”

绿色文字(价格上涨)>>>>> class =“ sc-1p4en3j-3 sc-1p4en3j-4 kZlsgN”

白色文字(无字串)>>>> class =“ sc-1p4en3j-3 sc-1p4en3j-6 czKdcJ”

第二个价格位置的类别地址固定,但是包含$符号。

我想获取股票价格并进行存储,以便以后进行数学运算。我尝试使用两个文本位置来获取价格。我的代码:

url= "https://www.binance.com/en/trade/LTC_USDT"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

试图从位置1获取价格:

newprice= soup.find('span', class_ = 'sc-1p4en3j-3 sc-1p4en3j-5 jFILqo')
newprice1= soup.find('span', class_ = 'sc-1p4en3j-3 sc-1p4en3j-4 kZlsgN')
newprice2= soup.find('span', class_ = 'sc-1p4en3j-3 sc-1p4en3j-6 czKdcJ')

print (str(newprice))
print (str(newprice1))
print (str(newprice2))

if I add .text to the 1st three lines above. it tells me: 'NoneType' object has no attribute 'text'

试图从位置2获取它:

newprice3= soup.find('span', class_ = 'sc-1p4en3j-7 eHDQUL')
print (str(newprice3))

输出:

None
None
None
None
评论
  • Me小懒虫
    Me小懒虫 回复

    You cannot use BeautifulSoup to retrieve the price because it's being generated using javascript and update via web-sockets, having said that, you should use the official Binance API, which is free.
    Here's an example to get the LTC price

    import requests
    url= "https://api.binance.com/api/v3/ticker/price?symbol=LTCUSDT"
    resp = requests.get(url).json()
    price = resp['price']
    # 43.45000000
    

    Demo