【问题标题】:Speed up multiple downloads with urllib2使用 urllib2 加速多次下载
【发布时间】:2018-03-05 12:57:37
【问题描述】:

我正在使用我编写的相当简单的代码从名为 ZINC 的数据库中下载多个 SMI 文件。但是,考虑到文件的大小(几 kb)和我的互联网连接,它的速度看起来并不是那么好。 有没有办法加快速度?

import urllib2


def job(url):
    ''' This function opens the URL and download SMI files from ZINC15'''

    u = urllib2.urlopen(url) # Open URL
    print 'downloading ' + url # Print which files is being downloaded
    with open('output.smi', 'a') as local_file:
        local_file.write(u.read())


with open('data.csv') as flist:
    urls = ['http://zinc15.docking.org/substances/{}.smi'.format(str(line.rstrip())) for line in flist]
    map(job, urls)

【问题讨论】:

标签: python download urllib2 python-2.x


【解决方案1】:
import threading
import Queue # the correct module name is Queue

MAX_THREADS = 10
urls = Queue.Queue()

def downloadFile():
    while not urls.empty()
        u = urls.get_nowait()
        job(u)


for url in your_url_list:
    urls.put(url)

for i in range(0, MAX_THREADS + 1):
    t = threading.Thread(target=downloadFile)
    t.start()

基本上是导入threading和queu模块,queu对象会保存跨多个线程使用的数据,每个线程都会执行downloadFile()函数。

容易理解,如果不明白,请告诉我。

【讨论】:

  • 你能解释一下 downloadFile() 函数是做什么的吗?
  • 队列模块在python 2中被命名为队列——OP使用的版本。 - From review
  • 下载文件正在检查队列对象以查看它是否有要处理的内容(在我们的示例中是要从中获取的 URL)如果它不是空的,则从队列中获取一个 URL 并将其传递给job() 这是你下载文件的方法,如果队列为空,我们什么也不做,导致运行 downloadFile() 的线程终止。
  • 非常有帮助,我用这个修改了我的代码,从 100kb/s 到 4~10m/s(我的网络很好,youtube-dl 可以达到 7~15m/s 左右)跨度>
猜你喜欢
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 2011-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多