Python HTTPPasswordMgrWithDefaultRealm error
Question: I am new to programming. I want write a parser for the beginning.

Code:

    
    
    import urllib
    import urllib.request
    url = 'https://example.com'
    username = 'login1'
    password = 'pass'
    p = urllib.request.HTTPPasswordMgrWithDefaultRealm()
    p.add_password(None, url, username, password)
    handler = urllib.request.HTTPPasswordMgrWithDefaultRealm(p)
    opener = urllib.build_opener(handler)
    urllib.install_opener(opener)
    f = urllib.request.urlopen(url)
    html = f.read()
    print ("html")
    

I get error in IDLE:

    
    
    Traceback (most recent call last):
      File "D:\project\parser.py", line 8, in <module>
        handler = urllib.request.HTTPPasswordMgrWithDefaultRealm(p)
    TypeError: __init__() takes 1 positional argument but 2 were given
    

Please help. Thanks.


Answer: If we look at the documentation for
`urllib.request.HTTPPassowrdMgrWithDefaultRealm`, the `__init__` method looks
like this:

    
    
    __init__(self)
    

That `self` is provided implicitly. You're trying to pass it a second
positional parameter (`p`), hence the error message.

Take a look at the Basic Authentication example in [the
documentation](https://docs.python.org/3/howto/urllib2.html#id5), which offers
the following example usage:

    
    
    # create a password manager
    password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
    
    # Add the username and password.
    # If we knew the realm, we could use it instead of None.
    top_level_url = "http://example.com/foo/"
    password_mgr.add_password(None, top_level_url, username, password)
    
    handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
    
    # create "opener" (OpenerDirector instance)
    opener = urllib.request.build_opener(handler)
    
    # use the opener to fetch a URL
    opener.open(a_url)
    
    # Install the opener.
    # Now all calls to urllib.request.urlopen use our opener.
    urllib.request.install_opener(opener)
    

