使用Python urllib超时下载文件?

Ned*_*ton 8 python urllib urllib2

Python初学者在这里.如果进程耗时超过500秒,我希望能够暂停下载视频文件.

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

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

Wol*_*lph 11

更好的方法是使用,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
Run Code Online (Sandbox Code Playgroud)


Voj*_*cky 7

虽然urlretrieve没有这个功能,你仍然可以为所有新的套接字对象设置默认超时(以秒为单位)。

import socket
import urllib    

socket.setdefaulttimeout(15)

try:
   urllib.urlretrieve ("http://www.videoURL.mp4", "filename.mp4")
except Exception as e:
   print("error")
Run Code Online (Sandbox Code Playgroud)


Dji*_*eus 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")
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 Python 3,那就是这样。如果您使用的是 Python 2,则应该使用 urllib2。