gpt4 book ai didi

python - http.client.RemoteDisconnected 用于 url 列表中的随机文件

转载 作者:行者123 更新时间:2023-11-30 22:08:46 25 4
gpt4 key购买 nike

我编写了一个脚本,使用 urllib.request 自动从 URL 列表中下载文件。

for url in addresses:
file_name = url.rsplit('/', 1)[-1]
file = os.path.join(directory, file_name)
urllib.request.urlretrieve(url, file)
print(" %-15s %-10s %25s" % ('--', file_name, 'downloaded'))

有时我会得到 raise RemoteDisconnected("远程结束关闭连接没有"
http.client.RemoteDisconnected:远程端关闭连接而没有响应
并且脚本停止。列表中有大约 100 个 url,我在下载第 3 个、第 25 个或第 89 个文件时可能会遇到该错误。我的意思是我可以得到第 n 个文件的错误,但是当我再次运行我的脚本时,第 n 个文件可以正确下载。这是随机的。

如何解决这个问题?

最佳答案

如果你想在失败后继续执行,请使用try except -

for url in addresses:
file_name = url.rsplit('/', 1)[-1]
file = os.path.join(directory, file_name)
try:
urllib.request.urlretrieve(url, file)
print(" %-15s %-10s %25s" % ('--', file_name, 'downloaded'))
print(count, '/', len(addresses))
except RemoteDisconnected:
print("url {} did not return a valid response".format(url))

现在要进一步解决这个问题,您可以继续尝试,直到 url 响应而不会像这样超时 -

valid_response = False
while not valid_response:
try:
urllib.request.urlretrieve(url, file)
valid_response = True
except RemoteDisconnected:
pass

这有点蛮力,但我们会继续尝试,直到得到有效的响应

关于python - http.client.RemoteDisconnected 用于 url 列表中的随机文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52090999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com