V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
chengxuan
V2EX  ›  Python

求助 python 报错误 给予解决者 100 元话费

  •  
  •   chengxuan · 2014-05-31 15:24:46 +08:00 · 6008 次点击
    这是一个创建于 3619 天前的主题,其中的信息可能已经有所发展或是发生改变。
    AttributeError: 'NoneType' object has no attribute 'json'
    36 条回复    2014-06-01 13:49:14 +08:00
    huyiwei
        1
    huyiwei  
       2014-05-31 15:28:18 +08:00
    汗~明显变量没有赋值
    phyng
        2
    phyng  
       2014-05-31 15:29:25 +08:00
    楼主赶紧贴代码。。。
    anheiyouxia
        3
    anheiyouxia  
       2014-05-31 15:36:27 +08:00 via Android
    虽然我没学过Python,但是这个错误不是很明显吗?要么你没初始化,要么在传这个东西的时候就把这个产量搞丢了了

    正确做法应该是直接看代码,看所有这个产量经过哪些操作,再看不懂,调试总可以了吧(如果你的IDE有调试功能的话)或者直接在所有用到这个产量的方法打印一下这个东西啊
    Crossin
        4
    Crossin  
       2014-05-31 15:43:40 +08:00
    XXX.json
    XXX为None
    manfay
        5
    manfay  
       2014-05-31 15:45:27 +08:00
    import json
    xiandao7997
        6
    xiandao7997  
       2014-05-31 15:46:48 +08:00 via Android
    4楼对的,空对象找不到属性
    xiaowangge
        7
    xiaowangge  
       2014-05-31 15:46:56 +08:00 via iPad
    import json
    binux
        8
    binux  
       2014-05-31 15:48:47 +08:00   ❤️ 1
    让我猜猜,你用的是requests?然后又自己封装了一层,应该返回 response object 的
    然后,没有 returen 或者 return 为空了,外面的函数接着调用了 ret.json() 于是失败了?
    RIcter
        9
    RIcter  
       2014-05-31 15:51:42 +08:00 via iPad   ❤️ 6
    ...这段错误要是有人能知道为什么报错..我给充话费..
    zoowii
        10
    zoowii  
       2014-05-31 16:13:34 +08:00
    @RIcter up
    zhy0216
        11
    zhy0216  
       2014-05-31 16:15:33 +08:00
    @RIcter 我觉得8楼是对的
    funagi
        12
    funagi  
       2014-05-31 16:19:33 +08:00
    >>> None.json
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'json'
    chengxuan
        13
    chengxuan  
    OP
       2014-05-31 16:26:15 +08:00
    @huyiwei @Reply @Crossin @binux 跪谢各位大神!
    我请求两个网站api。然后跑一会就报错挂啦。。
    会不会是请求太快,api数据太大,导致我抓取不到数据,所以报错呢?
    skydiver
        14
    skydiver  
       2014-05-31 16:38:06 +08:00
    @anheiyouxia 这么多产量。。。
    liushuaikobe
        15
    liushuaikobe  
       2014-05-31 16:47:22 +08:00   ❤️ 1
    @chengxuan
    产生这个错误的场景太多太多了,没有context别人靠猜测根本没办法给你找出错误原因。你出100块钱就是像@RIcter 说的那样,看谁能猜对bug代码的上下文。

    如果抓取是同步执行的,要么是API返回结果不是你想要的形式,要么是根本没访问到API就出Exception,print一下,一目了然。

    如果抓取是异步的,那就是你没把对结果的处理写在callback里,发出请求后立即对result做处理,这是result还是None。
    est
        16
    est  
       2014-05-31 16:52:20 +08:00
    NullReferenceException NullPointerException
    binux
        17
    binux  
       2014-05-31 17:11:48 +08:00   ❤️ 1
    @chengxuan 我继续猜
    请求api封装的时候,为了防止异常,是这么写的

    try:
    __return requests.post('http://some.api.com/')
    except:
    __pass

    当多次访问之后,requests 出现了
    ConnectionError: HTTPConnectionPool(host='some.api.com', port=80): Max retries exceeded with url: /
    异常,没有办法 return,于是,函数实际返回空

    后面处理没有做判断,亦然调用 ret.json(),于是报错
    anheiyouxia
        18
    anheiyouxia  
       2014-05-31 17:15:14 +08:00 via Android
    @skydiver 手机打字,九宫格拼音,产量和变量呃于是242654264,不要太在意这些细节≥﹏≤
    chengxuan
        19
    chengxuan  
    OP
       2014-05-31 17:34:24 +08:00
    @liushuaikobe
    @binux
    @Crossin
    源码贴出,跪谢各位大神。

    #coding=utf-8
    import time, re, requests, md5, urllib, urllib2, json ,sys ,os
    #sys.path.append(os.path.dirname(__file__).replace('\\','/'))
    from huobi import HuoBi
    from bitfinex import Bitfinex
    from configs import config,keys
    class getprice(object):
    def __init__(self):
    #获取动态配置
    self.huobi = HuoBi(keys['huobi']['key'],keys['huobi']['secretKey'])
    self.bitf = Bitfinex(keys['bitf']['key'],keys['bitf']['secretKey'])
    def buy_seller(self):
    p1 = self.get_huobi()
    pr1 = p1['sell']
    p2 = self.get_bitf()
    pr2 = p2['sell'] * config['rate']
    if pr1 > pr2:
    pre = (pr1 - pr2) / pr1 * 100
    if pre >= config['agio']:
    self.huobi_sell(p1['buy'])
    self.bitf_sell('buy',p2['sell'])
    else:
    pre = (pr2 - pr1) / pr2 * 100
    if pre >= config['agio']:
    self.huobi_buy(p1['sell'])
    self.bitf_sell('sell',p2['buy'])
    print("huobi : %s %s finex : %s ") % (pr1,pre,pr2)
    def get_huobi_seller(self):
    try:
    r = requests.get('http://market.huobi.com/staticmarket/depth_btc_json.js')
    return r
    except:
    time.sleep(18)
    self.get_huobi_seller()
    def get_bitf_seller(self):
    try:
    r = requests.get('https://api.bitfinex.com/v1/book/btcusd')
    return r
    except:
    time.sleep(18)
    self.get_bitf_seller()
    def get_huobi(self):
    r1 = self.get_huobi_seller()
    t = r1.json()
    p1 = t['asks'][-5]
    p2 = t['bids'][4]
    pr1 = float(p1[0])
    pr2 = float(p2[0])
    return {'buy':pr2,'sell':pr1}
    def get_bitf(self):
    r2 = self.get_bitf_seller()
    t = r2.json()
    p1 = t['asks'][4]
    p2 = t['bids'][4]
    pr1 = float(p1['price'])
    pr2 = float(p2['price'])
    return {'buy':pr2,'sell':pr1}
    def huobi_sell(self,price=''):
    #getattr(huobi,method)
    price = self.get_huobi()
    price = price['buy']
    info = self.huobi.sell(price,config['amount']) #{u'result': u'success', u'id': 18161354}
    print(info)
    def huobi_buy(self,price):
    info = self.huobi.buy(price,config['amount'])
    print(info)
    def bitf_sell(self,side='sell',price=''):
    """
    symbol (string): The name of the symbol (see `/symbols`).
    amount (decimal): Order size: how much to buy or sell.
    price (price): Price to buy or sell at. May omit if a market order.
    exchange (string): "bitfinex".
    side (string): Either "buy" or "sell".
    type (string): Either "market" / "limit" / "stop" / "trailing-stop" / "fill-or-kill" / "exchange market" / "exchange limit" / "exchange stop" / "exchange trailing-stop" / "exchange fill-or-kill". (type starting by "exchange " are exchange orders, others are margin trading orders)
    is_hidden (bool) true if the order should be hidden. Default is false.
    """
    price = self.get_bitf()
    price = price['buy']

    params = {
    "symbol":"btcusd",
    "amount" : str(config['amount']),
    "price" : str(price),
    "exchange" : "bitfinex",
    "side" : side,
    "type" : "exchange market",
    }

    info = self.bitf.order_new(params)
    print(info)
    x = getprice()
    while config['start']:
    x.buy_seller()
    time.sleep(18)
    smallghost
        20
    smallghost  
       2014-05-31 17:37:09 +08:00
    这100元话费还是有作用的,我是打酱油的
    binux
        21
    binux  
       2014-05-31 17:38:07 +08:00   ❤️ 1
    def get_huobi_seller(self):
    try:
    r = requests.get('http://market.huobi.com/staticmarket/depth_btc_json.js')
    return r
    except:
    time.sleep(18)
    self.get_huobi_seller()

    你看,except 里面没有 return 啊,`return self.get_huobi_seller()`
    虽然不建议,如果一直失败会导致爆栈的
    chengxuan
        22
    chengxuan  
    OP
       2014-05-31 17:42:32 +08:00
    @binux qq或者mail发给我[email protected]
    konakona
        23
    konakona  
       2014-05-31 17:45:23 +08:00
    =..= 来晚了啊!!!这么简单的东西虽然我是个phper也能解决啊!!!100块啊!!!
    RIcter
        24
    RIcter  
       2014-05-31 17:49:18 +08:00 via iPad
    @binux binux大大果然是大神....QAQ
    chengxuan
        25
    chengxuan  
    OP
       2014-05-31 17:49:58 +08:00
    @binux 在线等你。。
    YouXia
        26
    YouXia  
       2014-05-31 17:52:25 +08:00
    问题虽然简单,但是 @binux 大神的牛X之处就是没有上下文,能迅速猜出错误原因,这需要写了很多python代码,且踩过很多坑才能快速得到答案的。

    膜拜。
    zzNucker
        27
    zzNucker  
       2014-05-31 18:41:46 +08:00
    我是来拜 @binux 大神的
    lightening
        28
    lightening  
       2014-05-31 18:44:17 +08:00
    @binux 真厉害,猜都能猜对。代码缩进丢了还能读……
    song940
        29
    song940  
       2014-05-31 19:02:49 +08:00 via iPhone
    我又想吐槽 Python 的代码缩进语法了 。
    d0o0g
        30
    d0o0g  
       2014-05-31 19:10:22 +08:00
    哈哈,错误很明显,大家很踊跃,我是看这100块钱进来的
    shoumu
        31
    shoumu  
       2014-05-31 19:11:50 +08:00
    我也来膜拜@binux 大神
    zhy0216
        32
    zhy0216  
       2014-05-31 20:24:37 +08:00
    @binux 真大神也!!!!
    MrGba2z
        33
    MrGba2z  
       2014-05-31 20:39:36 +08:00
    @binux 膜拜一下大神

    这得踩过多少坑,写过多少代码才能猜出。。。
    vob636
        34
    vob636  
       2014-06-01 08:49:35 +08:00 via iPad
    蹲守v2多少年终于有缘见到@binux大神真面目一次!!
    afterain
        35
    afterain  
       2014-06-01 11:32:58 +08:00   ❤️ 1
    因为@binux对爬虫情有独钟~
    xuzhe
        36
    xuzhe  
       2014-06-01 13:49:14 +08:00
    这一百块引出个大神,值了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   928 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:33 · PVG 06:33 · LAX 15:33 · JFK 18:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.