• Python+selenium:get_screenshot_as_file截图代码和UserWarning: name used for saved screenshot does not match file type提醒


    使用get_screenshot_as_file,方便后面自动化截图和操作

    具体代码如下:

    # #!/usr/bin/python3
    # -*- coding: utf-8 -*-
    # @Time : 2020/8/5 13:59
    # @Author : Gengwu
    # @FileName: Screenshot.py
    # @Software: PyCharm
    
    from selenium import  webdriver
    from time import sleep
    
    driver=webdriver.Chrome()
    driver.get('https://www.baidu.com/')
    driver.maximize_window()
    sleep(2)
    
    driver.get_screenshot_as_file(r"C:UsersEDZDesktop附件文件aidu.jpg") #创建截图文件的路径
    
    #打开博客链接创建截图
    driver.get('https://www.cnblogs.com/gengwulovestudy/')
    driver.get_screenshot_as_file(r"C:UsersEDZDesktop附件文件oke.png")
    
    sleep(2)
    driver.quit()

    执行后可以看到截图正常,但是有个警告提醒

     警告提醒代码如下:

    C:UsersEDZDesktopselenium_demovenvScriptspython.exe C:/Users/EDZ/Desktop/selenium_demo/webdriver/Screenshot.py
    C:UsersEDZDesktopselenium_demovenvlibsite-packagesseleniumwebdriver
    emotewebdriver.py:1071: UserWarning: name used for saved screenshot does not match file type. It should end with a `.png` extension
      "type. It should end with a `.png` extension", UserWarning)
    
    Process finished with exit code 0

    通过点击警告链接查看源码如下:

         if not filename.lower().endswith('.png'):
                warnings.warn("name used for saved screenshot does not match file "
                              "type. It should end with a `.png` extension", UserWarning)
            png = self.get_screenshot_as_png()
            try:
                with open(filename, 'wb') as f:
                    f.write(png)
            except IOError:
                return False
            finally:
                del png
            return True

    发现

    if not filename.lower().endswith('.png') 如果不是以.png结尾,则会抛出警告

    我们代码里面截图有个是jpg格式的,会报一个警告,我们修改jpg为png,修改代码如下:
    driver.get_screenshot_as_file(r"C:UsersEDZDesktop附件文件aidu1.png") #创建截图文件的路径
    
    #打开博客链接创建截图
    driver.get('https://www.cnblogs.com/gengwulovestudy/')
    driver.get_screenshot_as_file(r"C:UsersEDZDesktop附件文件oke1.png")

    修改后查看执行结果没有报错

    截图图片正常:

     以上如果有问题欢迎随时讨论。

    Best Regards!
    Make a little progress every day!
  • 相关阅读:
    NC20282 棘手的操作(启发式合并)
    CF707D Persistent Bookcase(主席树+bitset)
    CF1473E Minimum Path(分层图+最短路)
    线段树优化建图2模板(暂无正确性保证)
    subprocess
    django中update_or_create()
    django中重复键值违反唯一键约束错误
    tox运行报C901错误解决办法
    gitlab搭建
    git命令
  • 原文地址:https://www.cnblogs.com/gengwulovestudy/p/13439552.html
Copyright © 2020-2023  润新知