python用selenium 验证码图片_Python +Selenium解决图片验证码登录或注册问题(推荐)
1. 解決思路
首先要獲得這張驗證碼的圖片,但是該圖片一般都是用的js寫的,不能夠通過url進行下載。
解決方案:截圖然后根據(jù)該圖片的定位和長高,使用工具進行裁剪
裁剪完畢之后,使用工具解析該圖片。
2. 代碼實現(xiàn)
2.1 裁剪出驗證碼圖片
裁剪圖片需要使用 Pillow 庫,進入pip包路徑后輸入安裝命令pip install Pillow:
之前安裝的時候忘記了截圖,只能夠截一張安裝后的圖片了 ╰(:з╰∠)_
安裝完成后,代碼實現(xiàn)方式如下:
#coding=utf-8
from selenium import webdriver
import time
from PIL import Image
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome()
# 進入該網(wǎng)站
driver.get("http://www2.nmec.org.cn/wangbao/nme/sp/root/account/signup.html")
# 能否在5s內(nèi)找到驗證碼元素,能才繼續(xù)
if WebDriverWait(driver,5).until(lambda the_driver:the_driver.find_element_by_id("CaptchaImg"), "查找不到該元素"):
# 對于一次截屏無法到截到驗證碼的情況,需要滾動一段距離,然后驗證碼的y坐標(biāo)也應(yīng)該減去這段距離
scroll = 500
js = "document.documentElement.scrollTop='%s'" %scroll
driver.execute_script(js)
# 截下該網(wǎng)站的圖片
driver.get_screenshot_as_file("E:/Python_selenium_advance/Picture/full.png")
# 獲得這個圖片元素
img_ele = driver.find_element_by_id("CaptchaImg")
# 得到該元素左上角的 x,y 坐標(biāo)和右下角的 x,y 坐標(biāo)
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 使用 圖鑒 商用接口來識別驗證碼
接口介紹網(wǎng)址:http://www.ttshitu.com/docs/python.html#pageTitle
調(diào)用該接口直接使用網(wǎng)頁上的接口文檔就行,代碼如下:
import json
import requests
import base64
from io import BytesIO
from PIL import Image
from sys import version_info
def 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 ,然后再導(dǎo)入該方法,直接使用即可:
from analysis_captcha import base64_api
def analysis_captcha(filename):
'''
使用 圖鑒 商用接口來識別指定位置的驗證碼圖片
:param filename: 驗證碼圖片位置
:return : 驗證碼文本
'''
img_path = filename
img = Image.open(img_path)
result = base64_api(uname='kaibin', pwd='******', softid='4545454', img=img)
return result
驗證碼識別可能會出錯,到時候再點擊驗證碼圖片換一張,然后重來即可。
總結(jié)
以上所述是小編給大家介紹的Python +Selenium實現(xiàn)圖片驗證碼登錄或注冊問題,希望對大家有所幫助!
本文標(biāo)題: Python +Selenium解決圖片驗證碼登錄或注冊問題(推薦)
本文地址: http://www.cppcns.com/jiaoben/python/299930.html
總結(jié)
以上是生活随笔為你收集整理的python用selenium 验证码图片_Python +Selenium解决图片验证码登录或注册问题(推荐)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。