Ubuntu 18.04 python 2.7 urllib 请求未获取数据

Ubuntu 18.04 python 2.7 urllib request not getting data

我有这个 python 脚本,可以在 ubuntu 16.04 上正常运行 但是它不会在 ubuntu 18.04 中获取数据,知道问题出在哪里吗? 没有错误。

    try:
        exchrate=float(json.loads(requests.get("http://api.coindesk.com/v1/bpi/currentprice.json").read())['bpi'][currency]['rate_float'])
        print exchrate
    except:
            try:
                print("Can not get data from coindesk.com")
                print("Trying to get data from coinbase.com")
                exchrate=float(json.loads(urllib2.urlopen("https://api.coinbase.com/v2/exchange-rates?currency=BTC").read())["data"]["rates"][currency])
                print exchrate
            except:
                try:
                    print("Can not get data from coinbase.com")
                    print("Trying to get data from blockchain.info")
                    exchrate=float(json.loads(urllib2.urlopen("https://blockchain.info/ticker").read())[currency]["last"])
                    print exchrate
                except:
                    print("Can not get data from blockchain.info")
                    print("Failed to get BTC exchange rate")
                    sys.exit()

输出:

Can not get data from coindesk.com
Trying to get data from coinbase.com
Can not get data from coinbase.com
Trying to get data from blockchain.info
Can not get data from blockchain.info
Failed to get BTC exchange rate

完整代码在这里:https://github.com/papampi/nvOC_by_fullzero_Community_Release/blob/Dual-cuda/WTM_SWITCHER

请求能够parse the JSON for you。试试这个:

response = requests.get("http://api.coindesk.com/v1/bpi/currentprice.json")
rate_float = response.json()['bpi']["USD"]['rate_float']
print(rate_float)

输出:

6366.6563

编辑:

No errors...

你默默地吞下抛出的任何错误。这是个坏主意,尤其是当您尝试调试时。不要这样做:

try:
    this_breaks()
except:
    try_other_thing()

您永远不会知道为什么 this_breaks() 完全坏了。要么不使用 try/except 让异常出现,要么至少打印出来:

try:
    this_breaks()
except Error as e:
    print("error: ", e)
    try_other_thing()

https://docs.python.org/3/tutorial/errors.html#handling-exceptions

由于您正在使用 Requests 库,因此您应该在每个 API 上使用它。 Requests提供了提取JSON的方法,所以不需要自己调用json模块

当多处都可能出错时,将它们捆绑在一行中并不是一个好主意。分阶段进行,这样您就可以准确地看到错误发生的位置,并适当地处理它。此外,使用未命名的 except 块很少是一个好主意:你可能会遇到一些你不知道如何处理的东西。

这是您的代码的重新组织版本。

import requests

currency = "USD"

apis = [
    {
        "name": "coindesk.com",
        "url": "https://api.coindesk.com/v1/bpi/currentprice.json",
        "keys": ("bpi", currency, "rate_float"),
    },
    {
        "name": "coinbase.com",
        "url": "https://api.coinbase.com/v2/exchange-rates?currency=BTC",
        "keys": ("data", "rates", currency),
    },
    {
        "name": "blockchain.info",
        "url": "https://blockchain.info/ticker",
        "keys": (currency, "last"),
    },
]

for d in apis:
    name, url, keys = d["name"], d["url"], d["keys"]
    print("Trying", name)
    try:
        req = requests.get(url)
        req.raise_for_status()
    except requests.exceptions.RequestException as e:
        print(e)
        print("Cannot get data from", name)
        continue

    try:
        # Extract the exchange rate
        data = req.json()
        for k in keys:
            data = data[k]
    except KeyError as e:
        print("Bad key!:", e)
        continue

    try:
        # Convert the exchange rate to a float.
        # Some APIs return it as a float, but coinbase.com returns
        # a string. This code also handles None, which in JSON is null
        # If you just want to print the rate, this conversion is not needed.
        rate = float(data) 
        print("Rate", rate)
        break
    except (ValueError, TypeError) as e:
        print("Invalid exchange rate data", data, type(data))
else:
    print("Failed to get BTC exchange rate")

典型输出

Trying coindesk.com
Rate 6440.64

更新:我改进了这段代码的错误处理。