基于python的-PIL定位截图

发布时间:2019-08-02 11:14:11编辑:auto阅读(2008)

    # -*- coding:utf-8 -*-
    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    
    # 安装PIL# pip install pillow
    from PIL import Image
    
    driver = webdriver.Firefox()
    driver.get('https://www.zhihu.com/signup')
    # 找到验证码图片
    ele = driver.find_element_by_xpath('//div[contains(@class,"Captcha")]/img')
    # 截取全屏
    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')
    # 定位到需要截取的地方
    img = img.crop((left, top, right, bottom))
    # 截取成功并保存到本地
    img.save('captcha.png')

关键字