Download a file providing username and password using Python

前端 未结 2 813
名媛妹妹
名媛妹妹 2020-12-18 09:18

My file named as \'blueberry.jpg\' begins downloading, when I click on the following url manually provided that the username and password are typed when asked: http://exampl

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 09:30

    Use requests, which provides a friendlier interface to the various url libraries in Python:

    import os
    import requests
    
    from urlparse import urlparse
    
    username = 'foo'
    password = 'sekret'
    
    url = 'http://example.com/blueberry/download/somefile.jpg'
    filename = os.path.basename(urlparse(url).path)
    
    r = requests.get(url, auth=(username,password))
    
    if r.status_code == 200:
       with open(filename, 'wb') as out:
          for bits in r.iter_content():
              out.write(bits)
    

    UPDATE: For Python3 get urlparse with: from urllib.parse import urlparse

提交回复
热议问题