selenium+pytesseract自動識別驗證碼實現自動健康打卡

步驟:打開瀏覽器–>登陸網站(識別驗證碼)–>自動化操作

難點:
1、驗證碼的識別:本來想用cookie,但是我們學校的網站的cookie中httponly = False,不能用這種方式繞過登陸。只能識別出驗證碼後登陸,過了登陸這關後便是一馬平川。2、網站元素的識別:世界上最遙遠的距離,不是生與死,而是你在我眼前,我卻識別不了你。selenium提供多種元素識別方式,常用的有id、name、class、xpath等,一種方式識別不了就換另一種,針對不同元素(不同網頁)識別的方式也不同,可參考https://blog.csdn.net/qq_32897143/article/details/80383502

環境要求:selenium pytesseract pillow
在命令行使用pip命令安裝以上第三方庫,默認的安裝方式很慢,使用鏡像網站安裝會快很多,直接複製下面這行到cmd
pip install --index https://pypi.mirrors.ustc.edu.cn/simple/ selenium

安裝完以上庫後,還需安裝chromedriver(selenium的瀏覽器驅動,edge或firefox也可)和tesseract(用於識別出驗證碼)
安裝chromedriver:打卡網站http://npm.taobao.org/mirrors/chromedriver/,找到對應自己的版本後下載,將chromedriver.exe文件複製到python的Scripts文件夾下(在cmd中用where python命令可找到自己的安裝路徑)
安裝tesseract:參照https://blog.csdn.net/showgea/article/details/82656515

from selenium import webdriver
from selenium.webdriver.support.select import Select #專門用來處理下拉框
import pytesseract
import os
import sys,time
from PIL import Image,ImageEnhance
website= 'https://www.xxx.com' #打卡的網站
img_address = ['C:\\Users\\HP--\\Pictures\\喜歡的照片\\image1.png'] #將驗證碼圖片下載下來後存放的地址,
 
driver = webdriver.Chrome()
driver.maximize_window()d
cnt = 0 #計數多少次識別驗證碼才成功

while True: #循環識別驗證碼直到成功
	driver.get(website)
	driver.get_screenshot_as_file(img_adress[0]) #將整個網頁截圖

	img =Image.open(img_address[0])
	box = (1217 , 496 , 1310 , 541)  #設置要裁剪的區域
	img = img.crop(box) 裁剪出只有驗證碼的圖片
	img.save(img_address[0])
	
	vc = pytesseract.image_to_string(img_address[0]) 保存驗證碼
	account = 'xxxxx'
	password = 'xxxxx'
	
	try:
		driver.find_element_by_name("account").send_keys(account)
		driver.find_element_by_name("password").send_keys(password)
		driver.find_element_by_name("rancode").send_keys(verfication_code)
		driver.find_element_by_class_name("login").click()

		if(driver.find_element_by_id("rancode-tips")): #這裏是驗證碼識別不正確點擊登陸後出現的錯誤信息
			cnt += 1
			continue
	except: #正確識別後成功登陸,退出while循環
		break 

try:
	driver.find_element_by_class_name("bdorange.bg_health").click()
	driver.find_element_by_link_text("健康打卡").click()
	driver.find_element_by_id("cph_right_ok_submit").click()

	opt = driver.find_element_by_id("cph_right_e_area")
	s = Select(opt)
	s.select_by_visible_text('廣東省') #以上三句處理下拉框

	driver.find_element_by_id('cph_right_e_location').send_keys('汕頭市')
	driver.find_element_by_id('cph_right_e_observation_0').click()
	driver.find_element_by_id('cph_right_e_health_0').click()
	driver.find_element_by_id('cph_right_e_temp').send_keys('36.6')
	driver.find_element_by_id('cph_right_e_survey01_0').click()
	driver.find_element_by_id('cph_right_e_submit').click()
except:
	pass

driver.quit()
print('經過{}次嘗試,自動健康打卡完成!'.format(cnt))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章