1. 程式人生 > >通過頁面截圖自動獲取驗證碼圖片

通過頁面截圖自動獲取驗證碼圖片

比較慢,必須要有驗證碼才能生效,否則報錯,測試的時候自己手動點出驗證碼吧。。

這個是參考了某個部落格的,但是地址我忘了,就這樣吧。。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

# 安裝PIL包
# pip install pillow
from PIL import Image
import time
driver = webdriver.Chrome()
driver.get('https://accounts.douban.com/login?alias=80713775%40qq.com&redir=https%3A%2F%2Fwww.douban.com%2F&source=index_nav&error=1013
') # 找到驗證碼圖片 time.sleep(15) ele = driver.find_element_by_xpath('//img[contains(@id,"captcha_image")]') # 擷取全屏 driver.save_screenshot('big.png') # 通過location定位x,y left = ele.location['x'] top = ele.location['y'] # 通過x,y的值拼接長和寬 right = left + ele.size['width'] bottom = top + ele.size['height'] # 建立img物件
# open()第一個引數 fp:filepath 檔案路徑 # 開啟剛擷取的全屏圖 img = Image.open('big.png') # 定位到需要擷取的地方 print(left,top,right,bottom) img = img.crop((left, top, right, bottom)) # 擷取成功並儲存到本地 img.save('hello.png')