我正在做一个代理支持的解析器,由于使用免费的代理,它们经常死掉,所以我的代码切换到其他代理,这里没有问题,但由于切换,我重新运行函数多次(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行,在(p.xpath(Goodsp))中的el中: AttributeError:'NoneType‘对象没有属性'xpath’
所以我的p变成了None,我应该怎么做才能把它保留下来呢?
发布于 2019-05-15 04:19:28
详述@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)
然后,生成的超文本标记语言将按照您的意图通过所有递归函数沿链向上反馈(或者我们是这样认为的,但无法确认,因为它不是MCVE
https://stackoverflow.com/questions/56137794
复制相似问题