怎么利用python实现循环登录不同账号?
因为我需要登录不同账号做一件同样的事情 , 做完这些事情后又退出登录 , 切换不同账号登录做同样的事情
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PIL import Image
import ddddocr
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome() #实例化对象
URL = "XXXXXXXXXXXXXXXXXX" #我的工作地址
username = ['xxxxxx','xxxxxx'] #储存的是账号
password = ['**********','*******'] #储存的密码
# 打开登录页面
def sta():
driver.maximize_window() # 将浏览器最大化
# 打开地址栏
driver.get(URL)
time.sleep(2) # 等待两秒加载网页
# 将验证码截图并保存
def sav():
# 1.将注册页面截图保存,这里需要以png结尾,其他图片格式会有warning
driver.save_screenshot("F:/screenshot/img.png")
# 2.定位到验证码图片元素
code_ele = driver.find_element(By.XPATH, "//img[@class='vcode']")
# 3.得到将元素的具体位置
x0 = code_ele.location["x"] # 565
y0 = code_ele.location["y"] # 478
x1 = code_ele.size["width"] + x0
y1 = code_ele.size["height"] + y0
img = Image.open("F:/screenshot/img.png")
image = img.crop((x0, y0, x1, y1)) # 左、上、右、下
image.save("F:/screenshot/code_img.png") # 将验证码图片保存为code_img.png
# 调用验证码识别库
def reco():
ocr = ddddocr.DdddOcr()
with open("F:/screenshot/code_img.png", 'rb') as f:
image = f.read()
res = ocr.classification(image)
return (res)
# 输入用户信息及验证码
def input1():
driver.find_element(By.XPATH, '//input[@placeholder="请输入用户名/手机"]').send_keys() # 输入账号
driver.find_element(By.XPATH, '//input[@placeholder="请输入密码"]').send_keys() # 输入密码
driver.find_element(By.XPATH, '//input[@placeholder="请输入验证码"]').send_keys(reco()) # 输入验证码
time.sleep(1)
driver.find_element(By.XPATH, '//button[@type="button"]').click() # 点击登录
time.sleep(2) # 等待跳转至首页
# 判断验证码是否正确
def while_login():
while True:
try:
driver.find_element(By.CLASS_NAME, "eb-sidebar-logo-collapsed") # 如果找到了首页这个元素则停止循环
break
# 若没有找到首页元素标识,则一直循环识别验证码,输入并登录
except:
sav()
reco()
driver.find_element(By.XPATH, '//input[@placeholder="请输入验证码"]').clear()
driver.find_element(By.XPATH, '//input[@placeholder="请输入验证码"]').send_keys(reco())
time.sleep(1)
driver.find_element(By.XPATH, '//button[@type="button"]').click()
time.sleep(2)
# 退出登录
def exit_login():
# 将鼠标悬停在设置图标上
mouse = driver.find_element(By.XPATH, '//i[@aria-label="图标: setting"]')
ActionChains(driver).move_to_element(mouse).perform()
# 点击退出登录
driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div/div[2]/div/div/div/div[3]/div[4]').click()
# 等待弹窗加载,确定退出
time.sleep(2)
driver.find_element(By.XPATH, '//button[@type="button" and @class="eb-btn eb-btn-primary"]').click()
if __name__ == '__main__':
sta()
sav()
input1()
while_login()
exit_login()
driver.close() # 关闭浏览器