title: selenium
date: 2022-02-28
tags: python
浏览器驱动程序
chromedriver = "C:/Program Files/Google/Chrome/Application/chromedriver_1"
下载地址,根据自己的chrome浏览器的版本选择下载即可: [Web](CNPM Binaries Mirror (npmmirror.com))
导入所需的库
import time
import os
from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException
import traceback
import ddddocr
from selenium.webdriver.common.action_chains import ActionChains
验证码处理
登录需要验证码验证
采用ocr识别
保存验证码图片到本地再经行处理
length=driver.find_elements_by_tag_name('svg')
print(len(length))
while(len(length)==1):
time.sleep(1)
# 查找验证码元素
code1= driver.find_element_by_tag_name('svg')
screenshot_as_bytes = code1.screenshot_as_png
# 图片地址
image1 = "elemenent1.png"
# 覆盖写入照片
with open(image1, 'wb') as f:
f.write(screenshot_as_bytes)
ocr = ddddocr.DdddOcr()
with open('elemenent1.png', 'rb') as f:
img_bytes1 = f.read()
res1 = ocr.classification(img_bytes1)
print(res1)
打开网站
os.environ["webdriver.ie.driver"] = chromedriver
driver=webdriver.Chrome() # 选择Chrome浏览器
driver.get('http://**.*****.cn/login') # 打开网站
#driver.get('https://www.baidu.com/')
driver.maximize_window() #最大化谷歌浏览器'''
定位用户名,密码元素
a=driver.find_element_by_xpath('//*[@id="app"]/div/div[3]/label/span[1]')
webdriver.ActionChains(driver).move_to_element(a).click(a).perform()
b=driver.find_element_by_xpath('//*[@id="app"]/div/div[4]/label/span[1]')
webdriver.ActionChains(driver).move_to_element(b).click(b).perform()# 点击用户名输入框
driver.find_element_by_xpath('//*[@id="app"]/div/button').click()
time.sleep(0.2)
driver.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div/div[1]/div[2]/div/input').click() # 点击用户名输入框
driver.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div/div[1]/div[2]/div/input').clear() #清空输入框
driver.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div/div[1]/div[2]/div/input').send_keys(username[i]) # 自动敲入用户名
print(username[i])
driver.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div/div[2]/div[2]/div/input').click() # 点击密码输入框
driver.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div/div[2]/div[2]/div/input').clear() #清空输入框
driver.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div/div[2]/div[2]/div/input').send_keys(password[i]) #
如果需要从本地上传图片,可以采用Autolt3
设置完成后,形成exe文件,添加到代码合适位置
os.startfile(r'D:/桌面文件/python/upload.exe')
time.sleep(5)
driver.find_element_by_xpath('//*[@id="app"]/div/div[2]/div[13]/div/div[2]/div/input').send_keys(tem)
driver.find_element_by_xpath('//*[@id="app"]/div/div[2]/div[15]/div/div[2]/div/input').send_keys(times)
bb=driver.find_element_by_xpath('//*[@id="app"]/div/div[2]/div[17]/button')
webdriver.ActionChains(driver).move_to_element(bb).click(bb).perform()
time.sleep(4)
#driver.close()
print(username[i]+"已完成")