【问题标题】:urllib.request.urlopen(url) with Authentication带有身份验证的 urllib.request.urlopen(url)
【发布时间】:2017-10-29 14:31:40
【问题描述】:

这几天我一直在玩漂亮的汤和解析网页。我一直在使用一行代码,它在我编写的所有脚本中都是我的救星。代码行是:

r = requests.get('some_url', auth=('my_username', 'my_password')).

但是...

我想用 (OPEN A URL WITH AUTHENTICATION) 做同样的事情:

(1) sauce = urllib.request.urlopen(url).read() (1)
(2) soup = bs.BeautifulSoup(sauce,"html.parser") (2)

我无法打开网址并阅读需要身份验证的网页。 我如何实现这样的目标:

  (3) sauce = urllib.request.urlopen(url, auth=(username, password)).read() (3) 
instead of (1)

【问题讨论】:

    标签: python python-3.x url beautifulsoup request


    【解决方案1】:

    你正在使用HTTP Basic Authentication

    import urllib2, base64
    
    request = urllib2.Request(url)
    base64string = base64.b64encode('%s:%s' % (username, password))
    request.add_header("Authorization", "Basic %s" % base64string)   
    result = urllib2.urlopen(request)
    

    所以你应该 base64 对用户名和密码进行编码,并将其作为 Authorization 标头发送。

    【讨论】:

    【解决方案2】:

    查看官方文档中的HOWTO Fetch Internet Resources Using The urllib Package

    # 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)
    

    【讨论】:

    • 请参阅问题中的第 (2) 行。我需要用漂亮的汤来解析酱汁。我如何使用您的代码实现这一目标?
    • AbstractBasicAuthHandler does not support the following scheme: 'Bearer'
    • @ChristianKönig Python38\lib\urllib\request.py", line 1014, in http_error_auth_reqed raise ValueError("AbstractBasicAuthHandler does not " ValueError: AbstractBasicAuthHandler does not support the following scheme: 'Digest'
    【解决方案3】:

    urllib3:

    import urllib3
    
    http = urllib3.PoolManager()
    myHeaders = urllib3.util.make_headers(basic_auth='my_username:my_password')
    http.request('GET', 'http://example.org', headers=myHeaders)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 2019-02-26
      • 2020-11-11
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 2018-05-12
      相关资源
      最近更新 更多