生活随笔
收集整理的這篇文章主要介紹了
Python + Selenium(九)- 解决图片验证码登录或注册问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 解決思路
首先要獲得這張驗證碼的圖片,但是該圖片一般都是用的js寫的,不能夠通過url進行下載。
解決方案:截圖然后根據該圖片的定位和長高,使用工具進行裁剪裁剪完畢之后,使用工具解析該圖片。
2. 代碼實現
2.1 裁剪出驗證碼圖片
裁剪圖片需要使用 Pillow 庫,進入pip包路徑后輸入安裝命令pip install Pillow:
之前安裝的時候忘記了截圖,只能夠截一張安裝后的圖片了 ╰(:з╰∠)_
安裝完成后,代碼實現方式如下:
#coding=utf-8
from selenium import webdriver
import time
from PIL import Image
from selenium.webdriver.support.wait import WebDriverWaitdriver = webdriver.Chrome()
# 進入該網站
driver.get("http://www2.nmec.org.cn/wangbao/nme/sp/root/account/signup.html")
# 能否在5s內找到驗證碼元素,能才繼續
if WebDriverWait(driver,5).until(lambda the_driver:the_driver.find_element_by_id("CaptchaImg"), "查找不到該元素"):# 對于一次截屏無法到截到驗證碼的情況,需要滾動一段距離,然后驗證碼的y坐標也應該減去這段距離scroll = 500js = "document.documentElement.scrollTop='%s'" %scrolldriver.execute_script(js)# 截下該網站的圖片driver.get_screenshot_as_file("E:/Python_selenium_advance/Picture/full.png")# 獲得這個圖片元素img_ele = driver.find_element_by_id("CaptchaImg")# 得到該元素左上角的 x,y 坐標和右下角的 x,y 坐標left = img_ele.location.get('x')upper = img_ele.location.get('y') - 500right = left + img_ele.size.get('width')lower = upper + img_ele.size.get('height')# 打開之前的截圖img = Image.open("E:/Python_selenium_advance/Picture/full.png")# 對截圖進行裁剪,裁剪的范圍為之前驗證的左上角至右下角范圍new_img = img.crop((left, upper, right, lower))# 裁剪完成之后保存到指定路徑new_img.save("E:/Python_selenium_advance/Picture/croped.png")time.sleep(2)driver.quit()
else:print("找不到驗證碼元素")
2.2 使用 圖鑒 商用接口來識別驗證碼
接口介紹網址:http://www.ttshitu.com/docs/python.html#pageTitle
調用該接口直接使用網頁上的接口文檔就行,代碼如下:
import json
import requests
import base64
from io import BytesIO
from PIL import Image
from sys import version_infodef base64_api(uname, pwd, softid, img):img = img.convert('RGB')buffered = BytesIO()img.save(buffered, format="JPEG")if version_info.major >= 3:b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')else:b64 = str(base64.b64encode(buffered.getvalue()))data = {"username": uname, "password": pwd, "softid": softid, "image": b64}result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)if result['success']:return result["data"]["result"]else:return result["message"]return ""
將其保存為一個單獨的 analysis_captcha.py ,然后再導入該方法,直接使用即可:
from analysis_captcha import base64_apidef analysis_captcha(filename):'''使用 圖鑒 商用接口來識別指定位置的驗證碼圖片:param filename: 驗證碼圖片位置:return : 驗證碼文本'''img_path = filenameimg = Image.open(img_path)result = base64_api(uname='kaibin', pwd='******', softid='4545454', img=img)return result
驗證碼識別可能會出錯,到時候再點擊驗證碼圖片換一張,然后重來即可。
最后總結一下:
如果你對此文有任何疑問,如果你也需要接口項目實戰,如果你對軟件測試、接口測試、自動化測試、面試經驗交流感興趣歡迎加入:軟件測試技術群:593462778,群里的免費資料都是筆者十多年測試生涯的精華。還有同行大神一起交流技術哦。
作者:暗潮洶涌
原創不易,歡迎轉載,但未經作者同意請保留此段聲明,并在文章頁面明顯位置給出原文鏈接。
總結
以上是生活随笔為你收集整理的Python + Selenium(九)- 解决图片验证码登录或注册问题的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。