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)


     
     

  • 相关阅读:
    sprigboot2.0升级修改配置细节记录
    MAC 以太坊环镜安装
    python3 scrapy+Crontab部署过程
    python3 程序问题解决列表
    位运算--通过总值分解出子值(解析子值)
    springboot war包在tomcat中运行
    【解决方法】macOS 安装Resin失败:fatal error: 'openssl/ssl.h' file not found
    MAC+VMware+CentOS 6.5 上网配置
    python报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0 解决方案
    解决mac+idea+tomcat没有日志输出问题
  • 原文地址:https://www.cnblogs.com/qiqi-yhq/p/12673493.html
Copyright © 2011-2022 走看看