通过页面截图自动获取验证码图片

比较慢,必须要有验证码才能生效,否则报错,测试的时候自己手动点出验证码吧。。

这个是参考了某个博客的,但是地址我忘了,就这样吧。。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

# 安装PIL包
# pip install pillow
from PIL import Image
import time
driver = webdriver.Chrome()
driver.get('https://accounts.douban.com/login?alias=80713775%40qq.com&redir=https%3A%2F%2Fwww.douban.com%2F&source=index_nav&error=1013')
# 找到验证码图片
time.sleep(15)
ele = driver.find_element_by_xpath('//img[contains(@id,"captcha_image")]')
# 截取全屏
driver.save_screenshot('big.png')
# 通过location定位x,y
left = ele.location['x']
top = ele.location['y']
# 通过x,y的值拼接长和宽
right = left + ele.size['width']
bottom = top + ele.size['height']
# 创建img对象
# open()第一个参数 fp:filepath 文件路径
# 打开刚截取的全屏图
img = Image.open('big.png')
# 定位到需要截取的地方
print(left,top,right,bottom)
img = img.crop((left, top, right, bottom))
# 截取成功并保存到本地
img.save('hello.png')

猜你喜欢

转载自www.cnblogs.com/mypath/p/10147360.html