我该如何使用Python和wget下载文件(视频)并将其保存到本地?由于有许多文件,因此我如何知道一个文件已经下载完毕,以便自动开始下载另一个文件?
谢谢。
谢谢。
简短回答。获取一个文件。
import urllib.request
urllib.request.urlretrieve("http://google.com/index.html", filename="local/index.html")
如果需要的话,你可以想办法循环执行那个操作。
urllib.request.urlretrieve("...")
:) - Chris Stenkamp不要这样做,请使用urllib2
或者urlgrabber
代替。
wget
?这个答案需要进一步扩展解释。 - muhukwget -rl1 -I /stuff/i/want/ http://url/<incrementing number>
是否不容易? - Seppo Erviäläos.system()
来生成一个wget
进程,它会阻塞直到wget
完成下载(或以错误退出)。因此,只需在循环中调用os.system('wget blah')
,直到您下载完所有文件。urllib2
或httplib
。您需要编写一定量的代码,但是由于可以重复使用单个HTTP连接来下载多个文件,而不是为每个文件打开新连接,所以性能更好。os.system()
不推荐使用,我们应该使用subprocess
作为替代方案,是这样吗?” - alper
#!/usr/bin/python
import sys
import threading
import urllib
from Queue import Queue
import logging
class Downloader(threading.Thread):
def __init__(self, queue):
super(Downloader, self).__init__()
self.queue = queue
def run(self):
while True:
download_url, save_as = queue.get()
# sentinal
if not download_url:
return
try:
urllib.urlretrieve(download_url, filename=save_as)
except Exception, e:
logging.warn("error downloading %s: %s" % (download_url, e))
if __name__ == '__main__':
queue = Queue()
threads = []
for i in xrange(5):
threads.append(Downloader(queue))
threads[-1].start()
for line in sys.stdin:
url = line.strip()
filename = url.split('/')[-1]
print "Download %s as %s" % (url, filename)
queue.put((url, filename))
# if we get here, stdin has gotten the ^D
print "Finishing current downloads"
for i in xrange(5):
queue.put((None, None))
download_url, save_as = queue.get()
中有一个错误。应该是 download_url, save_as = self.queue.get()
。 - disfated通过pypi安装wget http://pypi.python.org/pypi/wget/0.3
pip install wget
然后运行,就像文档中所述
python -m wget <url>