zoukankan      html  css  js  c++  java
  • 截图+存储图片

    Python+Selenium基础入门及实践

        Webdriver自带截图功能有两种,get_screenshot_as_file(),save_screenshot(),一般我习惯使用前者。使用这两种方式截图时传入文件存放路径名称即可截图成功。但是每一次截图时需要传入一个文件名,并且多次命名可能存在重复或者毫无章法。因此可以采用自动生成日期、时间来命名文件夹和文件名称可方便管理截图,并且调用截图函数时,不需要一次次的传参。
     
    语法:os.path.dirname(path)
    功能:去掉文件名,返回目录
     
    语法:time.strftime(format[,t])
    功能:返回可读字符串表示的当地时间
     
    获取当前目录:
    1、os.getcwd()
    2、os.path.abspath(os.path.dirname(__file__))
     
    获取上级目录:
    1、os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    2、os.path.abspath(os.path.dirname(os.getcwd()))
    3、os.path.abspath(os.path.join(os.getcwd(), ".."))
     
    获取上上级目录
    1、print os.path.abspath(os.path.join(os.getcwd(), "../.."))
     
     
    我这里生成在上级目录,以下为代码示例:

    # -*- coding:utf-8 -*-

    import random
    import time
    import os
    from selenium import webdriver

    def screenshot(self): # 生成年月份时分秒时间 picture_time
    = time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time())) print(picture_time) directory_time = time.strftime('%Y-%m-%d', time.localtime(time.time())) print(directory_time) # 打印上层目录 print(os.path.abspath(os.path.dirname(os.getcwd()))) # 获取当前文件的上层目录,并检查是否有directory_time文件夹,如果不存在则自动创建directory_time文件夹 try: file_path = os.path.abspath(os.path.dirname(os.getcwd())) + '\' + directory_time + '\' if not os.path.exists(file_path): os.makedirs(file_path) print('目录新建成功:%s' % file_path) else: print('目录已存在!') except BaseException as msg: print('新建目录失败:%s' % msg) try: picture_url = self.driver.get_screenshot_as_file(os.path.abspath(os.path.dirname(os.getcwd())) + '\' + directory_time + '\' + picture_time + '.png') print('%s:截图成功!' % picture_url) except BaseException as msg: print('截图失败:%s' % msg)


     
     

  • 相关阅读:
    前端打包利器:webpack工具
    asp.net 通过ajax方式调用webmethod方法使用自定义类传参及获取返回参数
    C#报错:创建调试信息文件 ……objDebugmodel.pdb: 拒绝访问
    ts 使用Visual Studio2012和TFS网站管理源代码
    Win7(包括32和64位)使用GitHub
    C#程序开发中经常遇到的10条实用的代码
    简单优化实现大数据量的重复判断和导入
    Asp.Net修改上传文件大小限制(修改web.config)
    XlFileFormat
    Excel 2007中的新文件格式
  • 原文地址:https://www.cnblogs.com/qiqi-yhq/p/12673493.html
Copyright © 2011-2022 走看看