python - 在 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 循环的开始重复该函数。
解决方案
如果您想在响应不满足您的条件时重试,您应该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
推荐阅读
- c# - 如何恢复 Unicode UTF-8 UTF-8_unicode_ci Mysql 转储文件?
- typescript - 在哪里可以获得 baconjs 的最新 typescript 类型定义?
- javascript - Dropzone.js 只上传两个文件
- intellij-idea - 如何在 IntelliJ IDE 中找到注释代码?
- dart - 在 AngularDart 应用程序中包含 Bootstrap 的最佳方法
- recursion - Erlang 模式匹配顺序
- python - 对于 Big-IP 操作系统,从 platform.system() 返回的字符串是什么?
- mysql - 向 MBRContains LineFromText 中的函数 st_geometryfromtext 提供的 GIS 数据无效
- r - 将字符列表添加到特定列范围内的列名开头
- android - Azure 移动服务和原生 Android Facebook 身份验证