python實例:實現用戶名,密碼,驗證碼輸入登錄網頁系統


環境准備:(python版本為3.6.0)

一、安裝selenium:pip install selenium

二、下載谷歌瀏覽器驅動chromedriver.exe

1、網址:http://chromedriver.storage.googleapis.com/index.html(根據chrome的版本下載對應的)

2、將下載好的chromedriver.exe解壓后放到指定目錄(我一般放在代碼目錄下)

三,安裝第三方庫,可參考文章:https://www.cnblogs.com/fppblog/p/11804196.html

pip install pillow

pip install pytesseract

引入:

from pytesseract import pytesseract
from selenium import webdriver
from PIL import Image

四,代碼實現

import time
import requests
from pytesseract import pytesseract
from selenium import webdriver
from PIL import Image


#創建一個瀏覽器對象
browser = webdriver.Chrome()
browser.maximize_window()
#打開登錄界面
browser.get('http://cloud.xxxx.com/login')

# 識別驗證碼
browser.save_screenshot('login.png')
#獲取驗證碼位置
codepng = browser.find_element_by_xpath('//*[@id="imgCheckCode"]')
location = codepng.location
size = codepng.size
#獲取驗證碼位置
left = location['x']
top = location['y']
bottom = top + size['height']
right = left + size['width']

#打開頁面截圖
login_png = Image.open('login.png')
code_png = login_png.crop((left,top,right,bottom)) #這里需要傳入一個元組
code_png.save('code.png')
#識別驗證碼
#第一步:通過內置模塊PIL打開文件
image = Image.open('code.png')
#第二步:識別圖片中的內容
image = image.convert('L') #轉化為灰度圖
threshold = 168 #設定的二值化閾值
table = [] #table是設定的一個表,下面的for循環可以理解為一個規則,小於閾值的,就設定為0,大於閾值的,就設定為1
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)

image = image.point(table,'1') #對灰度圖進行二值化處理,按照table的規則(也就是上面的for循環)
image.show()
result = pytesseract.image_to_string(image) #對去噪后的圖片進行識別
print('圖片內容為:',result)

#定位賬號密碼驗證碼輸入框
acc_input = browser.find_element_by_xpath('//*[@id="username"]')
time.sleep(2)
acc_input.send_keys('EPxxxx001')
pwd_input = browser.find_element_by_xpath('//*[@id="password"]')
time.sleep(2)
pwd_input.send_keys('123456')
code_input = browser.find_element_by_xpath('//*[@id="checkCode"]')
time.sleep(2)
code_input.send_keys(result)
time.sleep(5)

#點擊登錄按鈕
try:
browser.find_element_by_xpath('//*[@id="login"]/div[5]/button').click()
#判斷系統狀態
url = browser.current_url
resp = requests.get(url, timeout=5)
code = resp.status_code
print('登錄返回碼為:',code)
assert code == 200
except Exception as e:
time.sleep(5)
#關閉
browser.close()
print('發生錯誤,登錄失敗!')
else:
if url == 'http://cloud.xxxx.com/lamp/analysis/data':
print('登錄成功!')
else:
print('登錄失敗!')
time.sleep(3)
# 關閉
browser.close()

本文部分為博主原創,轉載請注明出處:https://www.cnblogs.com/fppblog/p/11797873.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM