Python:urllib2.HTTPError:HTTP错误401:未经授权 [英] Python: urllib2.HTTPError: HTTP Error 401: Unauthorized

查看:1639
本文介绍了Python:urllib2.HTTPError:HTTP错误401:未经授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图加载网页,但是遇到了这个问题.我确实有用户名和密码,但是我不知道如何在python代码中使用它们.我查了一下python教程,这就是我写的:

I was trying to load a web page, but I ran into this problem. I do have the username and password, but I don't know how to use them in python code. I looked up on python tutorial, and this is what I wrote:

import urllib2

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
username = 'user'
password = 'pass'
top_level_url = "www.something.com:80"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
opener.open('http://www.something.com/h/h.html')
urllib2.install_opener(opener)
response = urllib2.urlopen()
page = response.read()
print page

有什么问题吗?

推荐答案

这是有效的代码

import urllib2

url = 'http://www.abc.com/index.html'
username = 'user'
password = 'pass'
p = urllib2.HTTPPasswordMgrWithDefaultRealm()

p.add_password(None, url, username, password)

handler = urllib2.HTTPBasicAuthHandler(p)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)

page = urllib2.urlopen(url).read()

这篇关于Python:urllib2.HTTPError:HTTP错误401:未经授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆