Python:从 Pancakeswap API 拉取 URL 请求

Python: Pulling a URL request from Pancakeswap API

我提出了换Pancake的请求API,我只需要下面粗体字的价格的前6位数字。最终目标是在价格低于或高于 X 价格时收到通知。

这是我从 API 得到的:

{"updated_at":1644088600598,"data":{"name":"SugarBounce","symbol":"TIP","price":"0.389597450332099015858871009432","price_BNB":"0.0009419388066193731353156275432376"}}

我正在使用 BeautifulSoup 并请求图书馆。

url = 'https://api.pancakeswap.info/api/v2/tokens/0x40f906e19b14100d5247686e08053c4873c66192'
data = requests.get(url)
soup = BeautifulSoup(data.content, 'html.parser')

您可以通过以下方式获取价格的前6位数字

价格以字符串形式发送,因此您可以进行一些列表切片以获得您想要的数字。

import requests
import json
url = 'https://api.pancakeswap.info/api/v2/tokens/0x40f906e19b14100d5247686e08053c4873c66192'
data = requests.get(url).json()

price = float(data['data']['price'][:6]) # to get the first 6 digits of the price

虽然价格是浮动的,但将之前的价格与 API 通话中的新价格进行比较可能会更好。

让我们调用您从 API result 中获取的词典。现在您可以获取价格如下:

price_str = result['price']
firstdigits = price_str[:6]

数字将采用字符串格式。如果你需要一个浮动,只需使用

digits = float(firstdigits)