selenium自动化 | 借助百度AI开放平台识别验证码登录职教云

#通过借助百度AI开放平台识别验证码登录职教云
from PIL import Image
from aip import AipOcr
import unittest
#
driver.get(zjy_url)
driver.maximize_window()
#输入账号密码
ActionChains(driver)\
        .click(driver.find_element_by_name('userName')).send_keys('xxxx')\
        .click(driver.find_element_by_name('userPassword')).send_keys('xxxx')\
        .perform()
while True:
        scr_path='./pic/zjy_sreenshot.png'
        driver.find_element_by_name('photoCode').clear()
        driver.get_screenshot_as_file(scr_path)
        #获取验证码的大小(宽高)及位置
        location=driver.find_element_by_xpath('//*[@id="x-modify"]/div/img[2]').location
        size=driver.find_element_by_xpath('//*[@id="x-modify"]/div/img[2]').size
        #经测试,坐标不准确
        # print(location,size)
        left=int(location['x'])
        right=int(location['x']+size['width'])#
        top=int(location['y'])
        bottom=int(location['y']+size['height'])#
        #使用PIL的Image方法裁剪截屏并保存
        Image.open(scr_path).crop((397,325,522,361)).save(scr_path)
        #相关变量的定义
        AppID='xxxx'#百度应用账号ID
        APIKey='xxxx'#针对接口访问的授权方式
        SecretKey='xxxx'#密钥
        #初始化操作
        client=AipOcr(AppID,APIKey,SecretKey)
        img=open(scr_path,'rb').read()
        message=client.basicGeneral(img)#
        for i in message.get('words_result'):
            print('尝试验证码:',i.get('words'))
            if message.get('words_result') != []: driver.find_element_by_name('photoCode').send_keys(i.get('words'))
            else:driver.find_element_by_name('photoCode').send_keys('ok')
        driver.find_element_by_id('btnLogin').click()
        time.sleep(1)
        #验证是否成功
        if driver.title != "职教云":
                print('登录成功')
                break
        else:
                #https://www.cnblogs.com/jie-2019/p/11921365.html
                driver.find_element_by_css_selector('*[class="sgBtn ok"]').click()
                print('再次登录')
#登录成功之后弹出窗口,点击'我知道了'
driver.find_element_by_css_selector('*[class="ad-cancel-sp"]').click()

 

posted @ 2020-05-17 19:49  人人都爱小雀斑  阅读(432)  评论(0编辑  收藏  举报