使用Python urllib超时下载文件吗?

问题描述 投票:10回答:3

Python初学者在这里。如果该过程花费的时间超过500秒,我希望能够使我的视频文件下载超时。

import urllib
try:
   urllib.urlretrieve ("http://www.videoURL.mp4", "filename.mp4")
except Exception as e:
   print("error")

我如何修改代码以实现这一目标?

python urllib2 urllib
3个回答
12
投票

更好的方法是使用requests,因此您可以流式传输结果并轻松检查超时:

import requests

# Make the actual request, set the timeout for no data to 10 seconds and enable streaming responses so we don't have to keep the large files in memory
request = requests.get('http://www.videoURL.mp4', timeout=10, stream=True)

# Open the output file and make sure we write in binary mode
with open('filename.mp4', 'wb') as fh:
    # Walk through the request response in chunks of 1024 * 1024 bytes, so 1MiB
    for chunk in request.iter_content(1024 * 1024):
        # Write the chunk to the file
        fh.write(chunk)
        # Optionally we can check here if the download is taking too long

3
投票

urlretrieve没有该选项。但是您可以借助urlopen轻松地执行示例,并将结果写入文件中,如下所示:

request = urllib.urlopen("http://www.videoURL.mp4", timeout=500)
with open("filename.mp4", 'wb') as f:
    try:
        f.write(request.read())
    except:
        print("error")

这就是使用Python3。如果使用Python 2,则应该使用urllib2。


0
投票

您可以为新的套接字对象设置默认超时(以秒为单位。)>

import socket
import urllib    

socket.setdefaulttimeout(15)

try:
   urllib.urlretrieve ("http://www.videoURL.mp4", "filename.mp4")
except Exception as e:
   print("error")
© www.soinside.com 2019 - 2024. All rights reserved.