How to download a file over http with authorization in python 3.0, working around bugs?

前端 未结 2 2092
无人共我
无人共我 2020-12-16 20:07

I have a script that I\'d like to continue using, but it looks like I either have to find some workaround for a bug in Python 3, or downgrade back to 2.6, and thus having to

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 20:23

    Direct from the Py3k docs: http://docs.python.org/dev/py3k/library/urllib.request.html#examples

    import urllib.request
    # Create an OpenerDirector with support for Basic HTTP Authentication...
    auth_handler = urllib.request.HTTPBasicAuthHandler()
    auth_handler.add_password(realm='PDQ Application',
                              uri='https://mahler:8092/site-updates.py',
                              user='klem',
                              passwd='kadidd!ehopper')
    opener = urllib.request.build_opener(auth_handler)
    # ...and install it globally so it can be used with urlopen.
    urllib.request.install_opener(opener)
    urllib.request.urlopen('http://www.example.com/login.html')
    

提交回复
热议问题