获取验证码图片步骤

1. 使用selenium操作谷歌浏览器,打开目标网站
2. 对目标网站进行截图,并将图片保存到本地
3. 获取验证码元素节点在屏幕上的位置,即横纵坐标
4. 使用Image库读取保存的截图
5. 使用pillow模块抠出大图中的验证码 只截取元素节点位置对应部分

导入所需库和打开目标网站

from selenium import webdriver
from selenium.webdriver.common.by import By
from PIL import Image
bro = webdriver.Chrome(executable_path='./chromedriver.exe')  # 打开浏览器
bro.get('https://www.chaojiying.com/apiuser/login/')  # 打开目标网站
bro.implicitly_wait(10)  # 隐士等待
bro.maximize_window()  # 将浏览器全屏

image

网页截图保存

bro.save_screenshot('screenshot.png')  # 网页截图,保存

获取验证码元素位置

# 根据css选择器找验证码元素
code = bro.find_element(By.CSS_SELECTOR,'body > div.wrapper_danye > div > div.content_login > div.login_form > form > div > img')
# 左上角的位置
left = code.location['x']  # 1110
top = code.location['y']  # 291
# 右下角的位置
right = code.size['width'] + left  # 1290
bottom = code.size['height'] + top  # 341

读取截图、截取验证码图片和保存验证码图片

img = Image.open('screenshot.png')  # 读取全屏截图
img = img.crop((left, top, right, bottom))  # 截取验证码图片
img.save('code.png')  # 保存图片

代码整合

from selenium import webdriver
from selenium.webdriver.common.by import By
from PIL import Image
bro = webdriver.Chrome(executable_path='./chromedriver.exe')  # 打开浏览器
bro.get('https://www.chaojiying.com/apiuser/login/')  # 打开目标网站
bro.implicitly_wait(10)  # 隐士等待
bro.maximize_window()  # 将浏览器全屏

bro.save_screenshot('screenshot.png')  # 网页截图,保存

# 根据css选择器找验证码元素
code = bro.find_element(By.CSS_SELECTOR,'body > div.wrapper_danye > div > div.content_login > div.login_form > form > div > img')
# 左上角的位置
left = code.location['x']  # 1110
top = code.location['y']  # 291
# 右下角的位置
right = code.size['width'] + left  # 1290
bottom = code.size['height'] + top  # 341

img = Image.open('screenshot.png')  # 读取全屏截图
img = img.crop((left, top, right, bottom))  # 截取验证码图片
img.save('code.png')  # 保存图片