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

2024-04-26 07:52:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个基本的http身份验证后面刮一个页面。我可以很好地使用wget http://user:pass@example.com/path/to/the_thing。但是如果我试图通过urllib2访问它,它就没有授权。你知道吗

我通读了the documentationPython urllib2 HTTPBasicAuthHandler,这看起来应该行得通,但我得到了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)

我不完全确定我做错了什么。你知道吗


Tags: thetopathcomauthhttpexamplemy
1条回答
网友
1楼 · 发布于 2024-04-26 07:52:10

需要更多详细信息才能知道发生了什么错误,但这里有另一种语法您可能需要尝试:

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)

相关问题 更多 >