1. 解決思路
首先要獲得這張驗證碼的圖片,但是該圖片一般都是用的js寫的,不能夠通過url進行下載。
解決方案:截圖然后根據該圖片的定位和長高,使用工具進行裁剪
裁剪完畢之后,使用工具解析該圖片。
2. 代碼實現
2.1 裁剪出驗證碼圖片
裁剪圖片需要使用 Pillow 庫,進入pip包路徑后輸入安裝命令pip install Pillow:
之前安裝的時候忘記了截圖,只能夠截一張安裝后的圖片了 ╰(:з╰∠)_
安裝完成后,代碼實現方式如下:
#coding=utf-8from selenium import webdriverimport timefrom PIL import Imagefrom 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 = 500 js = "document.documentElement.scrollTop='%s'" %scroll driver.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') - 500 right = 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 jsonimport requestsimport base64from io import BytesIOfrom PIL import Imagefrom 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 ""
新聞熱點
疑難解答