基于Python的Selenium自动化— 实现验证码截取

一、截取验证码

selenium webdriver 的api中直接提供了截图的方法.但是是全屏,要实现对元素的截取,则需要绕一绕弯.

1、获取到元素的大小、元素的坐标
2、截取整屏
3、根据元素的坐标和大小,定位要剪裁的区域
4、使用图像库对元素区域进行剪裁

python代码实现:

driver.get_screenshot_as_file('a.jpg')
1
2
3
4
5
6
7
8
9
10
location = driver.find_element_by_id('validate-img').location
size = driver.find_element_by_id('validate-img').size
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
a = Image.open("a.jpg")
im = a.crop((left,top,right,bottom))
im.save('a.jpg')
time.sleep(1)

代码没有注释部分,解释起来就是上面的四个步骤