【问题标题】:Best way to download files simultaneously with Python?与 Python 同时下载文件的最佳方法?
【发布时间】:2021-08-15 16:15:55
【问题描述】:

我正在尝试使用 Python requests 模块同时发送 get 请求。

在寻找解决方案时,我遇到了很多不同的方法,包括grequestsgevent.monkeyrequests futuresthreadingmulti-processing...

关于速度和代码可读性,我有点不知所措,不知道该选择哪一个。

任务是尽可能快地从同一服务器下载

【问题讨论】:

    标签: python multithreading networking download python-requests


    【解决方案1】:
    def download(webpage):
        requests.get(webpage)
        # Whatever else you need to do to download your resource, put it in here
    
    urls = ['https://www.example.com', 'https://www.google.com','https://yahoo.com'] # Populate with resources you wish to download
    threads = {}
    
    if __name__ == '__main__':
        for i in urls:
            print(i)
            threads[i] = threading.Thread(target=download, args=(i,))
        for i in threads:
            threads[i].start()
        for i in threads:
            threads[i].join()
        print('successfully done.')
    

    上面的代码包含一个名为download 的函数,它表示您必须运行任何代码来下载您要下载的资源。然后会生成一个列表,其中包含您希望下载的 url - 请随意更改这些值。这被组装到包含线程的第二个字典中。这样您就可以在 url 字典中拥有任意数量的 url,并为它们中的每一个创建一个单独的线程。线程各自启动,然后加入。

    【讨论】:

      【解决方案2】:

      我会使用 threading,因为不需要像 multiprocessing 那样在多个内核上运行下载。
      所以写一个函数,其中有requests.get(),然后作为线程启动。

      但请记住,您的互联网连接必须足够快,否则不值得。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-06
        • 1970-01-01
        • 2010-09-14
        • 1970-01-01
        • 1970-01-01
        • 2019-03-05
        • 2023-03-15
        • 1970-01-01
        相关资源
        最近更新 更多