好久沒有學python了,反正各種理由吧(懶惰總會有千千萬萬的理由),最近網上學習了一下selenium,實現了一個簡單的自動登錄網頁,具體如下。
1.安裝selenium:
如果你已經安裝好anaconda3,直接在windows的dos窗口輸入命令安裝selenium:
python -m pip install --upgrade pip
查看版本pip show selenium
2.接著去http://chromedriver.storage.googleapis.com/index.html下載chromedriver.exe(根據chrome的版本下載對應的)
3.將下載好的chromedriver.exe解壓后放到指定目錄
4.安裝tesseract-ocr.exe 配置環境變量
5.安裝pytesseract : pip install pytesseract
6.python腳本
思路:6.1登錄頁面按F12檢查元素,獲取用戶名 密碼 驗證碼 驗證碼圖片的元素id
6.2.調用chromedriver
6.3.截取驗證碼圖片的位置
6.4.pytesseract識別圖片中字符,最后驗證碼識別為空!!???這個待解決
6.5.腳本如下:
from selenium import webdriverfrom PIL import Imageimport pytesseractimport os,timechromedriver = "D:/Program Files/Anaconda3/selenium/webdriver/chromedriver.exe" #這里寫本地的chromedriver 的所在路徑os.environ["webdriver.Chrome.driver"] = chromedriver #調用chrome瀏覽器driver = webdriver.Chrome(chromedriver)driver.get("http://xxxx.com") #該處為具體網址driver.refresh() #刷新頁面driver.maximize_window() #瀏覽器最大化#獲取全屏圖片,并截取驗證碼圖片的位置driver.get_screenshot_as_file('a.png')location = driver.find_element_by_id('imgValidateCode').locationsize = driver.find_element_by_id('imgValidateCode').sizeleft = location['x']top = location['y']right = location['x'] + size['width']bottom = location['y'] + size['height']a = Image.open("a.png")im = a.crop((left,top,right,bottom))im.save('a.png')time.sleep(1)#打開保存的驗證碼圖片image = Image.open("a.png")#圖片轉換成字符vcode = pytesseract.image_to_string(image)print(vcode)#填充用戶名 密碼 驗證碼driver.find_element_by_id("staffCode").send_keys("username")driver.find_element_by_id("pwd").send_keys("password")driver.find_element_by_id("validateCode").send_keys(vcode)#點擊登錄 driver.find_element_by_id("loginBtn").click()總結
以上所述是小編給大家介紹的Python實現網頁用戶名 密碼 驗證碼自動登錄功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林站長站網站的支持!
新聞熱點
疑難解答