python3 urllib 401_Python:urllib2.HTTPError:HTTP错误401:未经授权

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

Anything wrong?

解决方案

Here is working code

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值