python实现访问需要登陆的网页

一 首先使用flask 编写一个Web服务器,用于模拟基础验证页面。代码如下。

from flask import Flask
from flask import request
import base64
app = Flask(__name__)
def hasAuth(auth,response):
    if auth == None or auth.strip() == "":
        response.status_code = 401
        #注意下面这句'Basic realm="localhost"',等号前后不能有逗号,否则会报错401,authorization的错
        response.headers['WWW-Authenticate'] = 'Basic realm="localhost"'
        return False
    return True
@app.route("/")
def index():
    response = app.make_response('username or pwd error')
    print(request.headers)
    auth = request.headers.get('Authorization')
    print('Authorization:',auth)
    if hasAuth(auth,response):
        auth = str(base64.b64decode(auth.split(' ')[1]),'utf-8')
        values = auth.split(':')
        username = values[0]
        password = values[1]
        print('username:',username)
        print('passwd:',password)
        if username == 'Mary' and password == '1234':
            return 'success'
    return response

if __name__ == '__main__':
    app.run()

运行结果如下图所示:此时访问http://127.0.0.1:5000/  会出现用户名和密码的登陆框。

二 使用Authorization设置用户名和密码发送给服务端

from urllib import request, response
import base64
url = 'http://localhost:5000'
headers = {
    'User-Agent':'Mozilla/5.0 (Macinosh; Intel Mac OS X 10_14_3) AppleWeKit/537.36'
                 '(KHTML, like Gecko) Chrom/72.0.3626.109 Safari/537.36',
    'Host':'localhost:5000',
    'Authorization':'Basic' + str(base64.b64encode(bytes('Mary:1234','utf-8')),'utf-8')
}
req = request.Request(url=url,headers=headers,method='GET')
reponse = request.urlopen(req)
print(response.read().decode('utf-8'))

这段代码报错500,但是http://localhost:5000' 可以访问,暂时没有找到原因(哭。

成功运行的界面,

三 使用build_opener访问网页。

#!/usr/bin/env python3
#-*-coding=utf-8-*-
__author__='km'
from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_opener
from urllib.error import URLError
username = 'Mary'
password = '1234'
url = 'http://localhost:5000/'
p = HTTPPasswordMgrWithDefaultRealm()
p.add_password('localhost',url,username,password)
auth_header = HTTPBasicAuthHandler(p)
opener = build_opener(auth_header)
try:
    result = opener.open(url)
    html = result.read().decode('utf-8')
    print(html)
except URLError as e:
    print(e.reason)

运行结果如下图:报错401,怀疑是realm原因,经过调试发现走到的是服务器第一个if语句里。暂时没有找到原因(哭。

找到原因了,因为上面服务器的代码有问题('Basic realm="localhost"',等号前后不能有逗号,去掉逗号之后这个报错没有了。)

成功运行的服务器返回值:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值