文章目录
- 实战题目
- 解题方案
实战题目
使用python+selenium实现输入验证码的UI自动化。登录页面如图:
解题方案
验证码登录需要导入相关模块和库,本文使用的是opencv和ddddocr模块组合,导入方式采用pip3 install opencv-python
、pip3 install ddddocr
,成功安装即可。
代码:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from common import do_time
import os
from time import sleep
import ddddocr
# 设置浏览器
option = webdriver.ChromeOptions()
option.add_experimental_option("prefs", {
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True,
"credentials_enable_service": False,
"profile.password_manager_enabled": False
}) #初始化Chrome的时候,不弹出密码框
option.add_experimental_option('excludeSwitches', ['enable-automation']) #设置防止被检测为selenium
option.binary_location = r'D:\Software\Google\Chrome\Application\chrome.exe'
# 启动Chrome浏览器
driver = webdriver.Chrome(service=Service("../config/chromedriver.exe"), options=option)
driver.maximize_window()
driver.implicitly_wait(10)
# 打开登录网页
driver.get("https://sso-iot-uat.dianliantech.com/oauth/login")
sleep(3)
# 输入用户名和密码
driver.find_element(By.XPATH, '//*[@id="username"]').send_keys('username')
driver.find_element(By.XPATH, '//*[@id="password"]').send_keys('password')
# 验证码处理
# 找到验证码并将验证码以截图的方式保存
vcode_ele = driver.find_element('xpath', '//*[@id="verifyImg"]')
vcode_path = r'D:\Learn\pycharmProject\IOT\vcode\vcode.png' #定义保存路径
vcode_ele.screenshot(vcode_path) #截图保存至指定路径下
# 调用ddddocr框架,读取验证码,并填入输入框
ocr = ddddocr.DdddOcr()
with open(vcode_path, 'rb') as f:
img_bytes = f.read()
vcode = ocr.classification(img_bytes)
driver.find_element(By.XPATH, '//*[@id="verifyCode"]').send_keys(vcode)
# 点击登录按钮
driver.find_element(By.XPATH, '//*[@id="loginSubmit"]').click()