Skip to main content
 首页 » 编程设计

python之几次函数调用后变量的值消失

2024年11月24日8jpfss

我正在制作一个支持代理的解析器,因为使用免费代理,它们经常死掉,所以我的代码切换到其他代理,这里没有问题,但由于切换我重新运行函数多次(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 次然后重新连接时,我收到此错误:

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

所以我的 p var 变成了 None,我应该怎么做才能保留它?

请您参考如下方法:

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

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

但是,如果你改变 block

    except requests.exceptions.ConnectionError: 
        con(where) 

收件人:

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

然后生成的 HTML 将按照您的预期通过所有递归函数反馈到链中(或者我们相信,但无法确认,因为它不是 MCVE