为什么我的基本身份验证处理程序不起作用?

Why is my basic auth handler not working?

我想抓取基本 http 身份验证背后的页面。我可以使用 wget http://user:pass@example.com/path/to/the_thing 就好了。但是,如果我尝试通过 urllib2 访问它,它就没有授权。

我通读了 the documentation as well as ,这似乎应该有效,但我得到了 HTTP Error 401: Unauthorized。所以它不起作用。

import urllib2
from bs4 import BeautifulSoup

very_beginning = "http://www.example.com/mm/path/to/the_thing"
my_user = "user"
my_passwd = "hella_secret"


auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(
                realm="clinty",
                uri="http://example.com/mm/",
                user=my_user,
                passwd=my_passwd
                )
auth_opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(auth_opener)

try:
    soup = BeautifulSoup(urllib2.urlopen(very_beginning))
    # return soup
except Exception as error:
    print(error)

我不完全确定我在这里做错了什么。

需要更多详细信息才能知道出了什么问题,但这里是您可能想尝试的另一种语法:

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, my_user, my_passwd)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)

从那里您可以确认它正在使用:

auth_opener = urllib2.build_opener(handler)
urllib2.install_opener(auth_opener)

try:
    soup = BeautifulSoup(urllib2.urlopen(very_beginning))
    print("success")
except Exception as error:
    print(error)