通过Python使用wget

Cor*_*eIs 29 python linux

如何使用wget使用Python下载文件(视频)并在本地保存?会有一堆文件,所以如何知道一个文件被下载以便自动开始下载另一个文件?

谢谢.

Mar*_*ata 20

简答(简化).获取一个文件

 import urllib
 urllib.urlretrieve("http://google.com/index.html", filename="local/index.html")
Run Code Online (Sandbox Code Playgroud)

如有必要,您可以弄清楚如何循环.

  • 到目前为止,如果有人仍然需要这个,它似乎是 `urllib.request.urlretrieve("...")` :) (3认同)

Ign*_*ams 19

不要这样做.使用urllib2urlgrabber替代.

  • 这个答案需要扩大.为什么不应该使用`wget`? (11认同)
  • 因为它开始一个全新的过程只是为了做Python本身能够做的事情. (11认同)
  • 用这些库中的任何一个写`wget -rl1 -I/stuff/i/want/http:// url/<递增数>>是不是很重要? (7认同)
  • 因为它破坏了可移植性. (6认同)
  • wget通过VPN客户端工作,而urllib给我这个错误的https:urlopen错误隧道连接失败:需要407代理验证 (5认同)

Ada*_*eld 10

如果您使用它os.system()来生成进程wget,它将阻塞直到wget完成下载(或退出并出现错误).因此,只需os.system('wget blah')在循环中调用,直到下载完所有文件为止.

或者,您可以使用urllib2httplib.您将不得不编写一个非常重要的代码,但是您将获得更好的性能,因为您可以重用单个HTTP连接来下载许多文件,而不是为每个文件打开一个新连接.


McJ*_*eff 9

没理由使用os.system.避免在Python中编写shell脚本,并使用urllib.urlretrieve或类似的东西.

编辑...要回答问题的第二部分,您可以使用标准库Queue类设置线程池.由于您正在进行大量下载,因此GIL应该不是问题.生成要下载的URL列表并将其提供给工作队列.它将处理对工作线程的推送请求.

我正在等待数据库更新完成,所以我把它快速地放在一起.


#!/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))