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:\Users\EDZ\Desktop\附件文件\baidu.jpg") #创建截图文件的路径

#打开博客链接创建截图
driver.get('https://www.cnblogs.com/gengwulovestudy/')
driver.get_screenshot_as_file(r"C:\Users\EDZ\Desktop\附件文件\boke.png")

sleep(2)
driver.quit()

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

Python+selenium:get_screenshot_as_file截图代码和UserWarning: name used for saved screenshot does not match file type提醒_第1张图片

 

 警告提醒代码如下:

C:\Users\EDZ\Desktop\selenium_demo\venv\Scripts\python.exe C:/Users/EDZ/Desktop/selenium_demo/webdriver/Screenshot.py
C:\Users\EDZ\Desktop\selenium_demo\venv\lib\site-packages\selenium\webdriver\remote\webdriver.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:\Users\EDZ\Desktop\附件文件\baidu1.png") #创建截图文件的路径

#打开博客链接创建截图
driver.get('https://www.cnblogs.com/gengwulovestudy/')
driver.get_screenshot_as_file(r"C:\Users\EDZ\Desktop\附件文件\boke1.png")

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

Python+selenium:get_screenshot_as_file截图代码和UserWarning: name used for saved screenshot does not match file type提醒_第2张图片

 

 

截图图片正常:

Python+selenium:get_screenshot_as_file截图代码和UserWarning: name used for saved screenshot does not match file type提醒_第3张图片

 

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

Best Regards!
Make a little progress every day!

 

你可能感兴趣的:(Python+selenium:get_screenshot_as_file截图代码和UserWarning: name used for saved screenshot does not match file type提醒)