裁剪图片需要使用 Pillow 库,进入pip包路径后输入安装命令pip install Pillow
:
之前安装的时候忘记了截图,只能够截一张安装后的图片了 ╰(:з╰∠)_
安装完成后,代码实现方式如下:
#coding=utf-8
from selenium import webdriver
import time
from PIL import Image
from selenium.webdriver.support.wait import WebDriverWait
driver = 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("找不到验证码元素")
接口介绍网址: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_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 ,然后再导入该方法,直接使用即可:
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
验证码识别可能会出错,到时候再点击验证码图片换一张,然后重来即可。