python 访问带有web认证的页面
python 访问带有web认证的页面,经测试方法一可用!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#方法一
#————————————————————–
def request_auth_http(url, User = None, Pass = None):
import urllib2
# this creates a password manager
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, User, Pass)
# create the AuthHandler
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
pagehandle = urllib2.urlopen(url)
data = pagehandle.read()
pagehandle.close()
return data
#方法二
#————————————————————–
#auth = “Basic %s” % base64.encodestring(“%s:%s” % (User, Pass))[:-1]
#request.add_header(“User-Agent”, “Python-2.5”)
#request.add_header(“Authorization”,auth)
#opener = urllib2.build_opener()
#data = opener.open(request).read()
#print data
#htmlFile = urllib2.urlopen(request)
#htmlData = htmlFile.read()
#htmlFile.close()
#return htmlData
#————————————————————–
def main():
url = “https://2hei.net/login”
User = “user”
Pass = “passwd”
print request_auth_http(url,User,Pass)
#————————————————————–
if __name__ == “__main__”:
main()
实际的结果是,方法一正解,方法二页面返回401错误。
本文固定链接: https://www.2hei.net/2009/11/05/python_auth_web_http/ | 2hei.net
最活跃的读者