1、接上次内容,多种情况下,还需要通过验证码进行验证,于是添加验证码认证这块。
验证码登录需要导入相关模块和库,网络上验证码认证的模块也有多种,本人用的是opencv和ddddocr模块组合,导入方式采用pip3 install opencv-python、pip3 install ddddocr,成功安装即可:
import cv2
import numpy as np
import ddddocr
2、验证码处理,首先将页面的验证码截图以图片方式保存,读取照片并处理为灰色降噪,再进行保存。
# 找到验证码并将验证码以截图的方式保存
driver.find_element(By.XPATH, '//*[@id="img_vcode"]').screenshot("D:/vscode/test/picture/img.png")
# 读取彩色图像
image = cv2.imread('D:/vscode/SSLVPN/picture/img.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 保存处理后的图像为新文件
cv2.imwrite('D:/vscode/test/picture/gry.png', gray)
3、调用ddddocr框架,读取验证码,并填入输入框
ocr = ddddocr.DdddOcr()
with open('D:/vscode/test/picture/img.png', 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes)
print(res)
# 填入验证码
driver.find_element(By.NAME, 'vldcode').send_keys(res)
4、结合上节用户名和密码认证,完整代码如下:
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.chrome.options import Options
import re
import subprocess
import requests
import json
import os
import re
import base64
from PIL import Image
import pytesseract
import base64
from io import BytesIO
import cv2
import numpy as np
import ddddocr
# 参数:
ip = '192.168.3.198'
user = 'user1'
password = '123456'
print('开始登录网页')
# 设置Chrome浏览器跳过安全检查
chrome_options = Options()
chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument('--ignore-ssl-errors')
# 设置Chrome浏览器禁止证书检查
capabilities = DesiredCapabilities.CHROME.copy()
capabilities['acceptInsecureCerts'] = True
driver = webdriver.Chrome(options=chrome_options, desired_capabilities=capabilities)
# 启动Chrome浏览器并打开登录页面
# driver = webdriver.Chrome(options=chrome_options)
driver.get(f'https://{ip}')
time.sleep(3)
# 验证码处理
# 找到验证码并将验证码以截图的方式保存
driver.find_element(By.XPATH, '//*[@id="img_vcode"]').screenshot("D:/vscode/test/picture/img.png")
# 读取彩色图像
image = cv2.imread('D:/vscode/SSLVPN/picture/img.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 保存处理后的图像为新文件
cv2.imwrite('D:/vscode/test/picture/gry.png', gray)
ocr = ddddocr.DdddOcr()
with open('D:/vscode/test/picture/img.png', 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes)
print(res)
# 填入验证码
driver.find_element(By.NAME, 'vldcode').send_keys(res)
# 找到用户名和密码输入框并输入正确的用户名和密码
username_input = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "user_name")))
username_input.send_keys(f'{user}')
time.sleep(1)
password_input = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "password")))
password_input.send_keys(f'{password}')
time.sleep(1)
login_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "loginbtn")))
login_button.click()
time.sleep(30)