Python + selenium命名截图并保存到指定文件夹

1.0 需要导入pathlib的Path类:

from pathlib import Path

2.0 截图函数:
可以使用以下两种

driver.save_screenshot()
driver.get_screenshot_as_file()

3.0 实现:

i=1
scrpath='D:\\Ex3'  #指定的保存目录
capturename = '\\'+str(i) + '.png'  #自定义命名截图
wholepath=scrpath+capturename
if Path(scrpath).is_dir():  #判断文件夹路径是否已经存在
    pass    
else: 
    Path(scrpath).mkdir()   #如果不存在,创建文件夹
while Path(wholepath).exists():   #判断文件是否已经存在,也可使用is_file()判断
    i+=1
    capturename = '\\'+str(i) + '.png'
    wholepath = scrpath+capturename
driver.get_screenshot_as_file(wholepath) #不能接受Path类的值,只能是字符串,否则无法截图

猜你喜欢

转载自blog.csdn.net/u010654583/article/details/79469473