【问题标题】:Value of variable disappears after few function calls几次函数调用后变量的值消失
【发布时间】:2019-05-15 04:19:28
【问题描述】:

我正在制作一个支持代理的解析器,因为使用免费代理,它们经常死掉,所以我的代码切换到其他代理,这里没有问题,但是切换的原因是我多次重新运行函数 (2-7) 和我解析的数据消失了,我确定问题很愚蠢但我自己无法找到它,谢谢回复!

想一想,应该以某种方式缓存 var 结果,因为 var 只保存指向对象的链接,并且在几次重新运行后,链接重新应用或我的函数中重新运行自身的问题,请帮助获取它。

def take():
    #  here I take ip:port, submit form, check if online, etc
    return proxy


def con(where):
    auto = take()
    #  proxy dict
    try:
        page = requests.get(where, headers={"content-type": "text"}, proxies=proxydict)
        return html.fromstring(page.content)
    except requests.exceptions.ConnectionError:
        con(where)


goods = []
goodsp = "some xpath here"
for n in range(1, 51):
    p = con("https://site&page=%s" % n)
    for el in (p.xpath(goodsp)):
        goods.append(el.get("href"))

所以一切正常,但是当代理死掉 2-7 次然后重新连接时,我收到此错误:

Traceback(最近一次调用最后一次): 文件“C:/Users/mi/PycharmProjects/testone/ya.py”,第 67 行,在 对于 (p.xpath(goodsp)) 中的 el: AttributeError: 'NoneType' 对象没有属性 'xpath'

所以我的 p var 变成了 None,我应该怎么做才能随身携带?

【问题讨论】:

  • in con add return con(where) inside except
  • @depperm 哦,我的.... 非常感谢,你是我的英雄!如何将您的评论标记为解决方案?

标签: python


【解决方案1】:

要详细说明@depperm 的评论,问题可能是您的递归函数没有返回任何内容。例如,您的执行流程可能如下所示:

con(where) <- which DOESN'T return HTML to this one<-|
    -> error                                         | 
       -> con(where)                                 |<-to this call here-|
          -> error                                                        |
             -> con(where)                                                |
                 -> success -> returns HTML       ->        ->        ->  |

但是,如果你改变了块

    except requests.exceptions.ConnectionError:
        con(where)

收件人:

    except requests.exceptions.ConnectionError:
        return con(where)

然后,生成的 HTML 将按照您的意图通过所有递归函数反馈到链上(或者我们相信,但由于它不是 MCVE 而无法确认)

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多