首页 > 解决方案 > 在 while 循环中检查请求响应

问题描述

我正在使用grequests模块向网站发送多个请求。我想检查响应是否是我想要的,因为有时服务器无法正确回复。响应是一个简单的字符串。

这是其中一个网址的示例: http ://www.tsetmc.com/tsev2/data/instinfofast.aspx?i=22811176775480091&c=39+

我想检查每个响应的长度以及我得到的所有响应的长度。我尝试了以下代码:

def online_data():
    while True:
        try:
            l = []
            rs = (grequests.get(u, timeout = 1) for u in urls)
            requests = grequests.map(rs)
            for response in requests:
                l.append(response.text.split(','))
                response.close()
            for i in l:
                if len(i) > 13:
                    break
            for i in l[:14]:
                if i:
                    break
            if len(l) == len(symbols):
                break

        except AttributeError:
            time.sleep(2)
            continue

    return l

但我不确定我是否做对了。

在 if 语句中,我想检查我得到的响应是否是我想要的,如果不是,我想从 while 循环的开始重复该函数。

标签: python

解决方案


如果您想在响应不满足您的条件时重试,您应该raise AttributeError转到except语句,而不是跳出循环。

def online_data():
    while True:
        try:
            l = []
            rs = (grequests.get(u, timeout = 1) for u in urls)
            requests = grequests.map(rs)
            for response in requests:
                l.append(response.text.split(','))
                response.close()
            for i in l:
                if len(i) > 13:
                    raise AttributeError
            for i in l[:14]:
                if i:
                    raise AttributeError
            if len(l) == len(symbols):
                raise AttributeError

        except AttributeError:
            time.sleep(2)
            continue

    return l

推荐阅读