python截图(长图和短图)方法封装

长图截取方法

*截取长图方法必须是在浏览器无头模式下进行,不然截取不了长图

@allure.step('截长图,图片名-{model}')
    def get_image_long(self, url, model=None):
        """
        此方法需要重新打开浏览器,并且是无头模式下
        :param url:需要截图的链接
        :param model:图片名称
        :return:None
        """
        # 设置chrome开启的模式,headless就是无界面模式
        # 一定要使用这个模式,不然截不了全页面,只能截到你电脑的高度
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('headless')
        chrome_options.add_argument('window-size=1920x1080')#此处设置分辨率可以自己设置
        self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
        # 控制浏览器写入并转到链接
        self.driver.get(url)
        # 接下来是全屏的关键,用js获取页面的宽高,如果有其他需要用js的部分也可以用这个方法
        width = self.driver.execute_script("return document.documentElement.scrollWidth")
        height = self.driver.execute_script("return document.documentElement.scrollHeight")
        # 将浏览器的宽高设置成刚刚获取的宽高
        self.driver.set_window_size(width, height)
        # 获取本地路径
        cur_path = os.path.dirname(os.path.dirname(__file__))
        # screenshot_path是存放图片的路径,需要当前总目录下创建一个名为Screenshots的文件夹
        now_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        screenshot_path = os.path.join(cur_path, f'Screenshots\\{now_date}')
        if not os.path.exists(screenshot_path):
            os.mkdir(screenshot_path)
        # 当前时间
        date_now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
        # 路径
        filepath = '{}\\{}.png'.format(screenshot_path, model)
        logger.info("截图,图片名为:%s" % model)
        # 截图并关掉浏览器
        self.driver.get_screenshot_as_file(filepath)
        self.driver.close()

短图截取方法

@allure.step('截图,图片名-{model}')
    def get_image_short(self, model=None):
        # filepath = 指图片保存目录/model(页面功能名称)_当前时间到秒.png
        # 截图保存目录
        # 拼接日志文件夹,如果不存在则自动创建
        cur_path = os.path.dirname(os.path.realpath(__file__))
        now_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        screenshot_path = os.path.join(os.path.dirname(cur_path), f'Screenshots\\{now_date}')
        if not os.path.exists(screenshot_path):
            os.mkdir(screenshot_path)
        # 当前时间
        date_now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
        # 路径
        filepath = '{}\\{}.png'.format(screenshot_path, model, date_now)
        # *特此注意:用此方法截图避免了有浏览器自带弹框会遮挡页面导致截图失败,
        # *特此注意:self.driver.save_screenshot(filepath)这种方法截图不能截取有浏览器自带弹框的时候,即使关闭了弹框,依旧会报错
        # 电脑屏幕左上角坐标和右下角坐标
        bbox = (0, 0, 1920, 1080)#此处可根据需要设置参数
        # 按照传入的参数截图(坐标可自行设置)
        im = ImageGrab.grab(bbox)
        # 保存截图到指定位置
        im.save(filepath)
        logger.info("截图,图片名为:%s" % model)

完整代码

# 截图方法
import os
import allure
from PIL import ImageGrab
from selenium import webdriver
import time
from webdriver_manager.chrome import ChromeDriverManager

from Utils.log import Log

logger = Log()


class Screenshots(object):
    def __init__(self, driver):
        self.driver = driver

    @allure.step('截长图,图片名-{model}')
    def get_image_long(self, url, model=None):
        """
        此方法需要重新打开浏览器,并且是无头模式下
        :param url:
        :param model:
        :return:
        """
        # 设置chrome开启的模式,headless就是无界面模式
        # 一定要使用这个模式,不然截不了全页面,只能截到你电脑的高度
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('headless')
        chrome_options.add_argument('window-size=1920x1080')
        self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
        # 控制浏览器写入并转到链接
        self.driver.get(url)
        # 接下来是全屏的关键,用js获取页面的宽高,如果有其他需要用js的部分也可以用这个方法
        width = self.driver.execute_script("return document.documentElement.scrollWidth")
        height = self.driver.execute_script("return document.documentElement.scrollHeight")
        # 将浏览器的宽高设置成刚刚获取的宽高
        self.driver.set_window_size(width, height)
        # 获取本地路径
        cur_path = os.path.dirname(os.path.dirname(__file__))
        # screenshot_path是存放图片的路径
        now_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        screenshot_path = os.path.join(cur_path, f'Screenshots\\{now_date}')
        if not os.path.exists(screenshot_path):
            os.mkdir(screenshot_path)
        # 当前时间
        date_now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
        # 路径
        filepath = '{}\\{}.png'.format(screenshot_path, model)
        logger.info("截图,图片名为:%s" % model)
        # 截图并关掉浏览器
        self.driver.get_screenshot_as_file(filepath)
        self.driver.close()

    @allure.step('截图,图片名-{model}')
    def get_image_short(self, model=None):
        # filepath = 指图片保存目录/model(页面功能名称)_当前时间到秒.png
        # 截图保存目录
        # 拼接日志文件夹,如果不存在则自动创建
        cur_path = os.path.dirname(os.path.realpath(__file__))
        now_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        screenshot_path = os.path.join(os.path.dirname(cur_path), f'Screenshots\\{now_date}')
        if not os.path.exists(screenshot_path):
            os.mkdir(screenshot_path)
        # 当前时间
        date_now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
        # 路径
        filepath = '{}\\{}.png'.format(screenshot_path, model, date_now)
        # *特此注意:用此方法截图避免了有浏览器自带弹框会遮挡页面导致截图失败,
        # *特此注意:self.driver.save_screenshot(filepath)这种方法截图不能截取有浏览器自带弹框的时候,即使关闭了弹框,依旧会报错
        # 电脑屏幕左上角坐标和右下角坐标
        bbox = (0, 0, 1920, 1080)
        # 按照传入的参数截图(坐标可自行设置)
        im = ImageGrab.grab(bbox)
        # 保存截图到指定位置
        im.save(filepath)
        logger.info("截图,图片名为:%s" % model)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的封装是指将数据和对数据的操作进行封装,以达到保护数据、隐藏实现细节和简化调用的目的。常见的封装方式有函数和类两种。 函数封装: 函数封装是指将一段可重复使用的代码封装成一个函数,以便在程序中多次使用。函数封装的语法格式为: ``` def function_name(parameters): statements return value ``` 其中,`function_name`是函数名,`parameters`是函数的参数列表,`statements`是函数体,`return`语句用于返回函数的结果值。 例如,下面的代码中定义了一个函数`add_numbers`,用于计算两个数的和: ```python def add_numbers(a, b): result = a + b return result ``` 在程序中可以通过调用`add_numbers`函数来计算两个数的和: ```python x = 1 y = 2 sum = add_numbers(x, y) print(sum) # 输出3 ``` 类封装: 类封装是指将数据和对数据的操作封装在一个类中,以便在程序中多次使用。类封装的语法格式为: ``` class class_name: def __init__(self, parameters): self.data_member = value def method_name(self, parameters): statements return value ``` 其中,`class_name`是类名,`__init__`方法是构造函数,用于初始化类的成员变量,`data_member`是数据成员,`method_name`是方法名,`statements`是方法体,`return`语句用于返回方法的结果值。 例如,下面的代码中定义了一个类`Rectangle`,用于表示矩形,并封装了计算周长和面积的方法: ```python class Rectangle: def __init__(self, length, width): self.length = length self.width = width def perimeter(self): return 2 * (self.length + self.width) def area(self): return self.length * self.width ``` 在程序中可以通过创建`Rectangle`类的对象来计算矩形的周长和面积: ```python rect = Rectangle(5, 3) print(rect.perimeter()) # 输出16 print(rect.area()) # 输出15 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值