【问题标题】:Using wget via Python [duplicate]通过 Python 使用 wget [重复]
【发布时间】:2011-01-28 21:13:34
【问题描述】:

如何使用 wget 通过 Python 下载文件(视频)并将其保存在本地?会有一堆文件,怎么知道下载了一个文件,然后自动开始下载另一个文件呢?

谢谢。

【问题讨论】:

标签: python linux


【解决方案1】:

简答(简体)。获取一个文件

 import urllib.request
 urllib.request.urlretrieve("http://google.com/index.html", filename="local/index.html")

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

【讨论】:

  • 现在,如果还有人需要这个,好像是urllib.request.urlretrieve("...") :)
  • @ChrisStenkamp 看起来有一个完整的循环(python 2 的 urllib)->(python 2 的 urllib2)->(python 3 的 urllib)。这意味着目前的答案是针对 python 2 的,你的注意是让它在 python 3 上工作。
  • 它也能显示进度吗?
【解决方案2】:

不要这样做。请改用urllib2urlgrabber

【讨论】:

  • 这个答案需要扩展。为什么不应该使用wget
  • 因为它开始了一个全新的过程,只是为了做 Python 本身能够做的事情。
  • 因为它破坏了可移植性。
  • 用这些库中的任何一个编写wget -rl1 -I /stuff/i/want/ http://url/<incrementing number> 是否重要?
  • wget 通过 VPN 客户端工作,而 urllib 为我提供 https 的此错误:urlopen 错误隧道连接失败:需要 407 代理身份验证
【解决方案3】:

通过pypihttp://pypi.python.org/pypi/wget/0.3安装wget

pip install wget

然后运行,就像记录的那样

python -m wget <url>

【讨论】:

  • 对于其他发现这令人困惑的人,链接库不使用 wget。它使用 urllib。而且它目前不支持任何接近 wget (gnu.org/software/wget) 所做的事情。
【解决方案4】:

没有理由使用 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))

【讨论】:

  • download_url, save_as = queue.get() 中有错误。应该是download_url, save_as = self.queue.get()
【解决方案5】:

没有理由使用 python。避免使用 Python 编写 shell 脚本,而应使用 bash 或类似的东西。

【讨论】:

  • 用 Python 写一个 shell 脚本是可以的。如果您想快速完成某件事但又讨厌 bash 的语法,那么只需在 Python 中完成即可。如果你做一个更大的项目,那么是的,尽量避免这些外部调用。
  • Python 是一种很好的脚本语言。
【解决方案6】:

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

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

【讨论】:

  • 不建议使用os.system(),作为替代我们应该使用subprocess
猜你喜欢
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 2017-08-12
  • 2012-05-26
  • 2010-11-10
  • 1970-01-01
相关资源
最近更新 更多