get_screenshot_as_file()
save_screenshot()
get_screenshot_as_file()
该方式通过driver获取该方法,将截图要保存的路径写入,如果图片格式未添加.png,会返回False
from selenium import webdriver import time driver = webdriver.Chrome() driver.get("http://www.baidu.com") driver.maximize_window() time.sleep(2) try: pic_url = driver.get_screenshot_as_file(r"/Users/alice/PycharmProjects/Huazhu/Pic/.png") # 图片存储的路径 print("%s:截图成功!!!" %pic_url) except BaseException as msg: print(msg) driver.quit()
上述方法虽然可以实现截图的功能,但是图片文件的名称容易重复,不好区分,可以生成代码运行的当前时间,来做为图片名,这样就不会再出现该问题了,修改代码如下:
from selenium import webdriver import time driver = webdriver.Chrome() driver.get("http://www.baidu.com") driver.maximize_window() time.sleep(2) pic_name = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime(time.time())) print(pic_name) try: pic_url = driver.get_screenshot_as_file(r"/Users/alice/PycharmProjects/Huazhu/Pic/" + pic_name + '.png') print("%s:截图成功!!!" %pic_url) except BaseException as msg: print(msg) driver.quit()
运行结果如下
save_screenshot():实质上就是get_screenshot_as_file()