欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python自动化调用百度api解决验证码

时间:2021-09-17 09:39:13|栏目:Python代码|点击:

自动化测试验证码登陆的三种解决方式

1,找开发关闭验证码
2,找开发设置万能验证码
3,使用第三方接口识别验证?C不能100%识别,比自己搭建的ocr识别的识别率高很多

具体讲的就是第三种-调用百度云识别验证码:

from selenium import webdriver
from PIL import Image
import base64
import requests
import time

def baidu_api(Verification_code, AK, SK):#Verification_code验证码路径,AK,SK百度云的身份识别码
    chrome.get_screenshot_as_file('reg.png')  # 获取登陆页面的图片
    code_img = chrome.find_element_by_xpath(Verification_code)  # 找到验证码图片的位置
    img = Image.open('reg.png')# 保存图片
    c_img = img.crop((code_img.location['x'], code_img.location['y'], code_img.location['x'] + code_img.size['width'],
                      code_img.location['y'] + code_img.size['height']))  # 截取验证码图片
    c_img.save('reg_code.png')
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&' \
            'client_id='+AK+'&' \
            'client_secret='+ SK
    response = requests.get(host)
    token = response.json()['access_token']
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
    f = open('reg_code.png', 'rb')# 二进制方式打开图片文件
    img = base64.b64encode(f.read())
    params = {"image": img}
    access_token = token
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    dict_a = response.json()['words_result']
    if response:
        dict_a = eval(str(dict_a)[1:-1])#数据类型的格式转换
        dict_a = dict(dict_a)#转化为字典类型
        dict_a = dict_a['words']
        dict_a = "".join(dict_a.split())  # 使用一个空字符串合成列表内容生成新的字符串
        dict_a = dict_a.lower()#把大写字母改为小写字母
        return dict_a
    else:
        chrome.refresh()

chrome = webdriver.Chrome()#浏览器实例化
chrome.maximize_window()#最大化浏览器
chrome.get('自己登陆的网址')
test = baidu_api(Verification_code, AK, SK)#返回识别的验证码
chrome = webdriver.Chrome()
print(test)#验证码

百度云AK,SK的获取:
进入:百度云
点击立即使用――进行登陆――实名认证。

在这里插入图片描述

按着自己的需求选着,免费的基本上就够用了

在这里插入图片描述

这就是自己的AK和SK

然后写入在代码里给AK和SK就行了

上一篇:理解Python垃圾回收机制

栏    目:Python代码

下一篇:基于Python实现的微信好友数据分析

本文标题:python自动化调用百度api解决验证码

本文地址:http://www.codeinn.net/misctech/175652.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有