python+selenium实现自动识别验证码并登录

最近学习python+selenium实现网站的自动登录,但是遇到需要输入验证码的问题,经过查询百度收获了几种破解验证码的方式。

方式一)从万能的网友那收获了一个小众但非常实用的第3方库ddddocr,仅几行代码就可以帮你解决大部分的数字+字母验证码问题了。(PS:使用这个库还需要安装最新的opencv-python库)

首先需要安装一下这个库:pip install ddddocr,安装后使用示例代码就可以得到验证码字符串了

import ddddocr

ocr=ddddocr.DdddOcr()
with open(r'F:\Test\venv\vfi_code.png' ,'rb')as f:
    img_bytes =f.read()
res =ocr.classification(img_bytes)
print(res)

实现整个自动登录流程的思路是:

先打开登录页面,然后将整个页面截图,再截取验证码部分使用第3方库ddddocr进行破解,通过driver.find_element_by_xpath() 定位到用户名,密码,验证码的输入框模拟自动输入和模拟点击登录按钮成功登录。附上完整代码:

from selenium import webdriver
import time,ddddocr
from PIL import Image
driver=webdriver.Chrome()
driver.maximize_window()

def get_img_code():
    driver.get('http://192.168.11.55:12345/#/login')
    driver.save_screenshot('web_screen.png')
    page_snap_obj = Image.open('web_screen.png')
    img=driver.find_element_by_xpath('//*[@id="userLayout"]/div/div[1]/form/div[3]/div/div[1]/div[2]/img')  # 根据css选择器来获取元素列表,鼠标右键选择Copy-》selector
    time.sleep(1)
    location = img.location
    size = img.size
    left = location['x']
    top = location['y']
    right = left + size['width']
    bottom = top + size['height']
    image_obj = page_snap_obj.crop((left, top, right, bottom))
    img_code = image_obj.save('vfi_code.png')
    #image_obj.show()
    ocr1=ddddocr.DdddOcr()
    with open(r'F:\Test\venv\vfi_code.png','rb')as f:
        img_bytes=f.read()
    res=ocr1.classification(img_bytes)
    print(res)
    return res

if __name__ == '__main__':
    res=get_img_code()
    driver.find_element_by_xpath('/html/body/div/div/div/div/div[1]/form/div[1]/div/div[1]/div/input').clear()  #copy的xpth包含一些随机数字,每次页面加载时都会更改,选择copy full xpth可以解决
    driver.find_element_by_xpath('/html/body/div/div/div/div/div[1]/form/div[1]/div/div[1]/div/input').send_keys('ussername')
    driver.find_element_by_xpath('/html/body/div/div/div/div/div[1]/form/div[2]/div/div[1]/div/input').clear()
    driver.find_element_by_xpath('/html/body/div/div/div/div/div[1]/form/div[2]/div/div[1]/div/input').send_keys('password')
    driver.find_element_by_xpath('/html/body/div/div/div/div/div[1]/form/div[3]/div/div[1]/div[1]/div/input').clear()
    driver.find_element_by_xpath('/html/body/div/div/div/div/div[1]/form/div[3]/div/div[1]/div[1]/div/input').send_keys(res)
    time.sleep(3)
    driver.find_element_by_xpath('//*[@id="userLayout"]/div/div[1]/form/div[4]/div/button[2]/span').click()

方式二)待补充

 参考链接:https://blog.csdn.net/leenhem/article/details/121507694

posted @ 2022-09-08 15:35  沐小木  Views(2982)  Comments(0Edit  收藏  举报