Download a file providing username and password using Python

前端 未结 2 743
名媛妹妹
名媛妹妹 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:29

    I'm willing to bet you are using basic auth. So try doing the following:

    import urllib.request
    
    url = 'http://username:pwd@example.com/blueberry/download'
    
    data = urllib.request.urlopen(url).read()
    
    fo = open('E:\\quail\\' + url.split('/')[1] + '.jpg', 'w')
    print (data, file = fo)
    
    fo.close()
    

    Let me know if this works.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题