使用selenium截屏获取验证码

self.driver = Chrome(CHROME_DRIVER) #初始化对象
self.driver.set_window_size(1280, 1024) #设置窗口大小
self.driver.execute_script(
'localStorage.setItem("pre_appadmin_login_2541044284@qq.com",JSON.stringify(%s))' % self.local_storage)#设置localStorage本地缓存

self.driver.get_screenshot_as_file(os.path.join(BASE_DIR, 'yanzheng.png'))#获取当前窗口截屏并保存在程序文件根目录

image_position = self.driver.find_element_by_id('imgcaptcha')#获取验证码图片元素
left = image_position.location['x']#获取验证最左边位置
top = image_position.location['y']#获取验证码上边位置
right = left + image_position.size['width']#获取验证码右边位置
bottom = top + image_position.size['height']#获取验证码下边位置

open_img = Image.open('yanzheng.png')#打开屏幕截图
open_img = open_img.crop((left, top, right, bottom))#使用获取到的位置剪切图片
open_img.show()#显示图片
output = input('输入验证码结果: ')
原文地址:https://www.cnblogs.com/louzi/p/10411571.html