【问题标题】:why would python3 recursive function return null为什么python3递归函数会返回null
【发布时间】:2018-11-01 01:17:48
【问题描述】:

我有这个功能,当达到速率限制时会再次调用自己。它最终应该会成功并返回工作数据。它正常工作,然后速率限制按预期工作,最后当数据恢复正常时,我得到:

TypeError: 'NoneType' 对象不可下标

def grabPks(pageNum):
    # cloudflare blocks bots...use scraper library to get around this or build your own logic to store and use a manually generated cloudflare session cookie... I don't care ????

    req = scraper.get("sumurl.com/"+str(pageNum)).content
    if(req == b'Rate Limit Exceeded'):
        print("adjust the rate limiting because they're blocking us :(")
        manPenalty = napLength * 3
        print("manually sleeping for {} seconds".format(manPenalty))
        time.sleep(manPenalty)
        print("okay let's try again... NOW SERVING {}".format(pageNum))
        grabPks(pageNum)
    else:
        tree = html.fromstring(req)
        pk = tree.xpath("/path/small/text()")
        resCmpress = tree.xpath("path/a//text()")
        resXtend = tree.xpath("[path/td[2]/small/a//text()")
        balance = tree.xpath("path/font//text()")
        return pk, resCmpress, resXtend, balance

我试图将 return 移到 else 范围之外,但它会抛出:

UnboundLocalError: 赋值前引用了局部变量 'pk'

【问题讨论】:

    标签: python-3.x recursion


    【解决方案1】:

    如果您的顶级grabPks 受到速率限制,则不会返回任何内容。

    想一想:

    1. 致电grabPks()
    2. 您的速率受限,因此您进入 if 语句并再次调用 grabPks()
    3. 这次它成功了,所以grabPks() 将值返回给它上面的函数。
    4. 第一个函数现在退出 if 语句,到达函数末尾并且不返回任何内容。

    尝试在 if 块内使用 return grabPks(pageNum)

    【讨论】:

      【解决方案2】:

      好吧...我需要返回grabPKs 让它玩得更好...:

      def grabPks(pageNum):
          # cloudflare blocks bots...use scraper library to get around this or build your own logic to store and use a manually generated cloudflare session cookie... I don't care ?
      
          req = scraper.get("sumurl.com/"+str(pageNum)).content
          if(req == b'Rate Limit Exceeded'):
              print("adjust the rate limiting because they're blocking us :(")
              manPenalty = napLength * 3
              print("manually sleeping for {} seconds".format(manPenalty))
              time.sleep(manPenalty)
              print("okay let's try again... NOW SERVING {}".format(pageNum))
              return grabPks(pageNum)
          else:
              tree = html.fromstring(req)
              pk = tree.xpath("/path/small/text()")
              resCmpress = tree.xpath("path/a//text()")
              resXtend = tree.xpath("[path/td[2]/small/a//text()")
              balance = tree.xpath("path/font//text()")
              return pk, resCmpress, resXtend, balance
      

      【讨论】:

        猜你喜欢
        • 2022-06-29
        • 2021-12-23
        • 2018-06-30
        • 2019-05-30
        • 1970-01-01
        • 2021-11-13
        相关资源
        最近更新 更多