我想抓取基本HTTP身份验证后面的页面。我可以使用wget http://user:pass@example.com/path/to/the_thing
很好。但是,如果我尝试通过urllib2
访问它,则未授权。
我通读了the documentation和Python 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)
我不确定自己在做什么错。
答案 0 :(得分:0)
需要更多详细信息才能知道出了什么问题,但这是您可能想尝试的另一种语法:
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)