WebDriver中實現對特定的Web區域截圖方法
import pytesseract
from PIL import Image
image=Image.open('new.jpg')
vcode=pytesseract.image_to_string(image)
print vcode
二、但在使用python自動化測試中會遇到一個難點,驗證碼怎么獲取,python的webdriver API沒有這樣接口。
baidu查之,網上只有java的解決方案,python的貌似沒有,在這就將python的解決方案寫下,以供需要的人參考:
解決方法:
從頁面獲取驗證碼的坐標值得,使用PIL的Image模塊,截取特定的區域,代碼如下:
思路:將web節目截圖保存-->定位到驗證碼坐標-->從截圖中再進行驗證碼位置的截圖
from PIL import Image
import pytesseract
from selenium import webdriver
url='http://xxxxx.com'
driver = webdriver.Chrome()
driver.maximize_window() #將瀏覽器最大化
driver.get(url)
driver.save_screenshot('f://aa.png') #截取當前網頁,該網頁有我們需要的驗證碼
imgelement = driver.find_element_by_xpath('//img[@src="rand!loginRand.action"]') #定位驗證碼
location = imgelement.location #獲取驗證碼x,y軸坐標
size=imgelement.size #獲取驗證碼的長寬
rangle=(int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']))
#寫成我們需要截取的位置坐標
i=Image.open("f://aa.png") #打開截圖
frame4=i.crop(rangle) #使用Image的crop函數,從截圖中再次截取我們需要的區域
frame4.save('f://frame4.jpg')
qq=Image.open('f://frame4.jpg')
text=pytesseract.image_to_string(qq).strip() #使用image_to_string識別驗證碼
print text