【问题标题】:Removing quotes from re.findall output从 re.findall 输出中删除引号
【发布时间】:2020-01-10 19:41:10
【问题描述】:

我正在尝试使用 Python 3 从我的 re.findall 输出中删除引号。我尝试了各种论坛的建议,但没有按预期工作,最终想到自己在这里问。

我的代码:

import requests
from bs4 import BeautifulSoup
import re
import time

price = [];

while True:
    url = "https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT"
    page = requests.get(url)
    soup = BeautifulSoup(page.content, 'html.parser')
    data = soup.prettify()
    for p in data:
        match = re.findall('\d*\.?\d+',data)
        print("ETH/USDT",match)
        price.append(match)
        break

match 的输出给出: ['143.19000000']。我希望它像:[143.1900000] 但我不知道该怎么做。

我遇到的另一个问题是标价会像单个列表一样附加每个对象。所以price 的输出例如是[[a], [b], [c]]。我希望它像[a, b, c] 我在解决这两个问题时遇到了一些麻烦。

谢谢:)

【问题讨论】:

    标签: python python-3.x list append


    【解决方案1】:

    将来自requests.get() 的响应解析为 JSON,而不是使用 BeautifulSoup:

    import requests
    
    url = "https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT"
    response = requests.get(url)
    response.raise_for_status()
    
    data = response.json()
    print(data["price"])
    

    【讨论】:

    【解决方案2】:

    获取浮点数而不是字符串:

    float_match = [float(el) for el in match]
    

    获取列表而不是列表列表:

    for el in float_match:
        price.append(el)
    

    【讨论】:

      猜你喜欢
      • 2014-03-19
      • 2015-09-28
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2023-01-25
      • 1970-01-01
      相关资源
      最近更新 更多