import ddddocr
from selenium import webdriver
from selenium.webdriver.common.by import By
from del_png import del_png
import time
driver = webdriver.Chrome()
time.sleep(5)
class Login:
def login(self):
# 打开登录页,
driver.get("登录页URL")
driver.maximize_window()
driver.implicitly_wait(2)
# 定位到验证码元素,因为验证码是以base64格式保存,所有需要先提取出验证码,保存成.png格式图片
el = driver.find_element(By.XPATH, '//div[@class="****"]/img')
# 将当前元素的屏幕截图保存为PNG图像文件
el.screenshot('./image.png')
# 识别验证码
ocr = ddddocr.DdddOcr()
with open("image.png", "rb") as f:
image = f.read()
res = ocr.classification(image)
# 定位元素,进行登录操作,注意输入账号、密码、验证码之间一定要设置等待,不然太快,识别出来的验证码准确率低
driver.find_element(By.XPATH, '//input[@pla="请输入账号"]').send_keys("*****")
time.sleep(1)
driver.find_element(By.XPATH, '//input[@pla="请输入密码"]').send_keys("*****")
time.sleep(1)
driver.find_element(By.XPATH, '//input[@pla="验证码"]').send_keys(res)
time.sleep(1)
driver.find_element(By.XPATH, '//button[@class="*****"]').click()
time.sleep(3)
# 获取cookies,添加cookies,这样就可以访问登录后的页面
get_cookie = driver.get_cookies()
for cookie in get_cookie:
driver.add_cookie(cookie)
if __name__ == '__main__':
Login().login()