繁体   English   中英

如何在 Python 中的某个时间后结束循环中的请求?

[英]How can I end a request in a loop after a certain time in Python?

我的 Python 程序应该(或已经可以)向网站列表发送请求以测试它们是否存在。 然后它应该将结果(无论它是否存在)保存在列表中或之后保存在文件中。 到目前为止,它运作良好。 但是对于某些网站,我总是收到一条错误消息,如下所示:

requests.exceptions.ReadTimeout: HTTPConnectionPool(host='www.oderwald.de', port=80): Read timed out. (read timeout=60)

我认为问题在于该网站只是不发送响应并一直询问该程序。 到目前为止,我的程序如下所示:

import requests
from requests.exceptions import ConnectionError
with open("list_website.txt") as infile:
   list = [list.strip() for list in infile]


list_ge = []
list_ne = []
x=0
n=0 
g=0
i=0

for i in range(len(list)):
    try:
        request = requests.get('http://www.' + list[i] + ".de")
    except ConnectionError:
        list_ne.append(list[i])
        g=+1
        file = open('not_working.txt','a')
        file.write(list[i]+ "\n")
    else:
        list_ge.append(list[i])
        n=+1
        file2 = open('works.txt','a')
        file2.write(liste[i] + "\n")

print(list_ge)
print(list_ne)

有谁知道我该如何解决这个问题? 提前谢谢了。

编辑:

要使异常提前返回(不是默认的 60 秒),请更改该行

request = requests.get('http://www.' + list[i] + ".de")

request = requests.get('http://www.' + list[i] + ".de", timeout = 2) ,其中 2 是您最多愿意等待的秒数。

首发帖如下:

您尝试访问的网站 (www.oderwald.de) 在指定的时间内(在您的情况下为 60 秒)没有响应,因此这种行为是可以预料的。 由于它只是一个例外,您可以使用except语句来处理它。 见下文:

try:
    request = requests.get('http://www.' + list[i] + ".de")
except requests.exceptions.ReadTimeout:
    print("Read timeout occurred")
    # The website exists but does not respond.
    # Decide to which category you assign it.

list()指的是内置的 Python function,您将在此行中覆盖它: list = [list.strip() for list in infile] 请改用另一个变量名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM