Python: urllib2.HTTPError: HTTP Error 401: Unauthorized

前端 未结 2 376
忘了有多久
忘了有多久 2021-02-03 11:26

I was trying to load a web page, but I ran into this problem. I do have the username and password, but I don\'t know how to use them in python code. I looked up on python tutori

相关标签:
2条回答
  • 2021-02-03 11:50

    I think you can use requests module which would make it be more easy for you.

    import requests
    username = 'user'
    password = 'pass'
    url = 'http://www.example.com/index.html'
    r = requests.get(url, auth=(username, password))  
    page = r.content
    print page
    
    0 讨论(0)
  • 2021-02-03 12:08

    Here is working code

    import urllib2
    
    url = 'http://www.abc.com/index.html'
    username = 'user'
    password = 'pass'
    p = urllib2.HTTPPasswordMgrWithDefaultRealm()
    
    p.add_password(None, url, username, password)
    
    handler = urllib2.HTTPBasicAuthHandler(p)
    opener = urllib2.build_opener(handler)
    urllib2.install_opener(opener)
    
    page = urllib2.urlopen(url).read()
    
    0 讨论(0)
提交回复
热议问题