How do I download a file over HTTP using Python?

前端 未结 25 2990
感动是毒
感动是毒 2020-11-21 07:17

I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I\'ve added to iTunes.

The te

25条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 07:40

    In 2012, use the python requests library

    >>> import requests
    >>> 
    >>> url = "http://download.thinkbroadband.com/10MB.zip"
    >>> r = requests.get(url)
    >>> print len(r.content)
    10485760
    

    You can run pip install requests to get it.

    Requests has many advantages over the alternatives because the API is much simpler. This is especially true if you have to do authentication. urllib and urllib2 are pretty unintuitive and painful in this case.


    2015-12-30

    People have expressed admiration for the progress bar. It's cool, sure. There are several off-the-shelf solutions now, including tqdm:

    from tqdm import tqdm
    import requests
    
    url = "http://download.thinkbroadband.com/10MB.zip"
    response = requests.get(url, stream=True)
    
    with open("10MB", "wb") as handle:
        for data in tqdm(response.iter_content()):
            handle.write(data)
    

    This is essentially the implementation @kvance described 30 months ago.

提交回复
热议问题