【发布时间】:2018-07-03 21:18:25
【问题描述】:
我想抓取一个位于基本 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)
我不完全确定我在这里做错了什么。
【问题讨论】:
-
为此使用
requests库更简单。来自the docs 的示例:requests.get('https://api.github.com/user', auth=('user', 'pass'))
标签: python python-2.7 basic-authentication