Python中的Webdriver截图

73 投票
15 回答
139669 浏览
提问于 2025-04-17 10:28

在Windows上使用Python的Selenium Webdriver截图时,截图会直接保存在程序所在的路径。有没有办法把这个.png文件保存到一个特定的文件夹里呢?

15 个回答

10

是的,我们可以通过Python的webdriver来获取.png格式的截图。

如果你在使用Python的webdriver,可以使用下面的代码。这非常简单。

driver.save_screenshot('D\folder\filename.png')
35

这个内容是受到一个讨论的启发(同样的问题在Java中):使用Selenium WebDriver截屏

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')
browser.quit()
90

使用 driver.save_screenshot('/path/to/file')driver.get_screenshot_as_file('/path/to/file') 来保存截图:

import selenium.webdriver as webdriver
import contextlib

@contextlib.contextmanager
def quitting(thing):
    yield thing
    thing.quit()

with quitting(webdriver.Firefox()) as driver:
    driver.implicitly_wait(10)
    driver.get('http://www.google.com')
    driver.get_screenshot_as_file('/tmp/google.png') 
    # driver.save_screenshot('/tmp/google.png')

撰写回答