简体   繁体   English

属性错误:“ NoneType”对象没有属性“ find”

[英]Attribute Error: 'NoneType' object has no attribute 'find'

I keep having issues when trying to run this code. 尝试运行此代码时,我一直遇到问题。 Had some help but still not working. 有一些帮助,但仍然无法正常工作。 Please help :) 请帮忙 :)

Full code : 完整代码:

#!/usr/bin/env python3
from __future__ import print_function
try:
    import pymarketcap
    import decimal
    from operator import itemgetter
    import argparse
except Exception as e:
    print('Make sure to install {0} (pip3 install {0}).'.format(str(e).split("'")[1]))
    exit()

# arguments and setup
parser = argparse.ArgumentParser()
parser.add_argument('-m','--minimum_vol',type=float,help='Minimum Percent volume per exchange to have to count',default=1)
parser.add_argument('-p','--pairs',nargs='*',default=[],help='Pairs the coins can be arbitraged with - default=all')
parser.add_argument('-c','--coins_shown',type=int,default=10,help='Number of coins to show')
parser.add_argument('-e','--exchanges',nargs='*',help='Acceptable Exchanges - default=all',default=[])
parser.add_argument('-s','--simple',help='Toggle off errors and settings',default=False,action="store_true")
args = parser.parse_args()
cmc = pymarketcap.Pymarketcap()
info = []
count = 1
lowercase_exchanges = [x.lower() for x in args.exchanges]
all_exchanges = not bool(args.exchanges)
all_trading_pairs = not bool(args.pairs)
coin_format = '{: <25} {: >6}% {: >10} {: >15} {: <10} {: <10} {: <15} {: <5}'

if not args.simple:
    print('CURRENT SETTINGS\n* MINIMUM_PERCENT_VOL:{}\n* TRADING_PAIRS:{}\n* COINS_SHOWN:{}\n* EXCHANGES:{}\n* ALL_TRADING_PAIRS:{}\n* ALL_EXCHANGES:{}\n'.format(args.minimum_vol,args.pairs,args.coins_shown,lowercase_exchanges,all_trading_pairs,all_exchanges))
# retrieve coin data
for coin in cmc.ticker():
    try:
        markets = cmc.markets(coin["id"])
    except Exception as e:
        markets = cmc.markets(coin["symbol"])
    best_price = 0

    best_exchange = ''
    best_pair = ''
    worst_price = 999999
    worst_exchange = ''
    worst_pair = ''
    has_markets = False
    for market in markets:
        trades_into = market["pair"].replace(str(coin["symbol"])," ").replace("-"," ")
        if market['percent_volume'] >= args.minimum_vol and market['updated'] and (trades_into in args.pairs or all_trading_pairs) and (market['exchange'].lower() in lowercase_exchanges or all_exchanges):
            has_markets = True
            if market['price_usd'] >= best_price:
                best_price = market['price_usd']
                best_exchange = market['exchange']
                best_pair = trades_into
            if market['price_usd'] <= worst_price:
                worst_price = market['price_usd']
                worst_exchange = market['exchange']
                worst_pair = trades_into
    if has_markets:
        info.append([coin['name'],round((best_price/worst_price-1)*100,2),worst_price,worst_exchange,worst_pair,best_price,best_exchange,best_pair])
    elif not args.simple:
        print(coin['name'],'had no markets that fit the criteria.')

    print('[{}/100]'.format(count),end='\r')
    count += 1

# show data
info = sorted(info,key=itemgetter(1))[::-1]
print(coin_format.format("COIN","CHANGE","BUY PRICE","BUY AT","BUY WITH","SELL PRICE","SELL AT","SELL WITH"))
for coin in info[0:args.coins_shown]:
    print(coin_format.format(*coin))

I keep getting this 2 errors : 我不断收到这2个错误:

  File "./run", line 33, in <module>
    markets = cmc.markets(coin["id"])
  File "/Users/alex/anaconda3/lib/python3.6/site-packages/pymarketcap/core.py", line 296, in markets
    marks = html.find(id="markets-table").find("tbody").find_all('tr')
AttributeError: 'NoneType' object has no attribute 'find'

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "./run", line 35, in <module>
    markets = cmc.markets(coin["symbol"])
  File "/Users/alex/anaconda3/lib/python3.6/site-packages/pymarketcap/core.py", line 296, in markets
    marks = html.find(id="markets-table").find("tbody").find_all('tr')
AttributeError: 'NoneType' object has no attribute 'find'

Any help would be tremendously appreciated. 任何帮助将不胜感激。 Thank you Received some great help before on my previous question but still no solution yet. 谢谢之前在我之前的问题上得到了很大的帮助,但仍然没有解决方案。

Any help would be tremendously appreciated. 任何帮助将不胜感激。 Thank you Received some great help before on my previous question but still no solution yet. 谢谢之前在我之前的问题上得到了很大的帮助,但仍然没有解决方案。

I think the issue is that, if for some coin there is just nothing to be found (no matter if you use coin["id"] or coin["symbol"] ), which can be caused by dead links which are built into the ticker module (coinmarketcap.com/currencies/). 我认为问题是,如果对于某些硬币,找不到任何东西(无论您使用coin["id"]还是coin["symbol"] ),这可能是由内置的无效链接引起的ticker模块(coinmarketcap.com/currencies/)。 In this case 在这种情况下

markets = cmc.markets(coin["id"])

markets = cmc.markets(coin["symbol"])

will both throw an AttributeError. 都将抛出AttributeError。 You should change your code to 您应该将代码更改为

for coin in cmc.ticker():
    try:
        # this call can fail
        markets = cmc.markets(coin["id"])
    except AttributeError as e:
        try:
            # second call could also fail
            markets = cmc.markets(coin["symbol"])
        except AttributeError as e1:
            print("Nothing found for " + coin["id"])
            continue #skip this coin?
    best_price = 0

I tried your code and it failed for a coin called janus for which, when you try the link manually, a PageNotFound is displayed, which would explain why it doesn't work to. 我尝试了您的代码,但对于名为janus的硬币失败了,当您手动尝试链接时,将显示PageNotFound ,这将解释为什么它不起作用。

NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None . NoneType意味着实际上没有None ,而不是您认为正在使用的任何Class或Object的实例。 That usually means that an assignment or function call up above failed or returned an unexpected result. 这通常意味着在上面的赋值或函数调用失败或返回了意外结果。

For Further investigation, I'd suggest you to print the response and it's type of the following expression: 为了进一步调查,我建议您打印响应及其以下表达式的类型:

for coin in cmc.ticker():
    try:
        markets = cmc.markets(coin["id"])
    except Exception as e:
        markets = cmc.markets(coin["symbol"])
    best_price = 0
print(markets)
print(type(markets))

This wont solve your problem, but might give you an insight of the Line of Code that is troubling you. 这不会解决您的问题,但是可能使您了解困扰您的代码行。 And you can further debug it as to where you are getting it wrong. 您还可以根据错误原因对它进行进一步调试。 And if the problem persists, you can edit your question and post the further evaluated code/traceback call, which will help us(the community members) to help you in solving your problem. 并且,如果问题仍然存在,您可以编辑问题并发布进一步评估的代码/回溯电话,这将帮助我们(社区成员)帮助您解决问题。

Usually, there are data types in python which you cannot iterate through and might require to either typecast it in some way which is iterable(eg. Dictionaries, Lists) or use attributes to access a value at a given index in your case. 通常,python中存在无法迭代的数据类型,可能需要以某种可迭代的方式(例如,字典,列表)对它进行类型转换,或者在您的情况下使用属性来访问给定索引的值。

Hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM