Python中的Webdriver截图功能

71
使用Selenium Webdriver在Windows上使用Python进行截图时,截图会直接保存到程序的路径中,有没有办法将.png文件保存到特定的目录中?
15个回答

88

使用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')

1
嗨,driver.save_screenshot('/path/to/file')在Windows上可以工作,但是driver.get_screenshot_as_file('/path/to/file')不行。(是的,我改成了“\”)。但这很有帮助,谢谢。你们有什么想法吗,如何使用selenium检查google的ReCaptcha?即使HTML生成<div class="google-recaptcha">或其他内容,您也无法选择任何元素... JS脚本也不起作用。为了澄清一下,我的意思不是解决reCaptcha中的图像,而只是检查复选框“我不是机器人”。 - Tommy L
1
@TommyL:save_screenshot调用get_screenshot_as_file,所以如果一个可行,另一个也应该可行。 - unutbu
1
@TommyL:关于recaptcha - 尝试搜索“selenium click google recaptcha”之类的内容。有许多潜在的线索,例如这个。如果这对您不起作用,您可以考虑发布一个新问题 - 包括您的代码,以便我们了解您尝试了什么以及出了什么问题。 - unutbu
还有一件事对我非常有帮助,如果你需要改变图像尺寸,只需在使用 driver.set_window_size(1366, 728) 拍摄快照之前设置窗口大小即可。 - srdg

35

受此主题启发(针对Java的同一问题):使用Selenium WebDriver进行屏幕截图

from selenium import webdriver

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

10

是的,我们可以使用Python webdriver获取扩展名为.png的屏幕截图。

如果您正在使用Python Webdriver,则可以使用以下代码。非常简单。

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

7
这将会截取屏幕并将其保存在指定名称的目录中。
import os
driver.save_screenshot(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'NameOfScreenShotDirectory', 'PutFileNameHere'))

拥有一个格式良好的代码来回答问题是很棒的,但通常最佳实践是在其中包含一些解释。 - sniperd
2
“这将会截取屏幕并将其放置在所选名称的目录中。” 对于大多数人来说,这应该很清楚了。 - Ger Mc
NameError: name 'file' is not defined - youssef mhiri

7
driver.save_screenshot("path to save \\screen.jpeg")

5

虽然这个问题现在并不存在,但我也曾遇到过类似的问题,我的解决方式是:

看起来 'save_screenshot' 在创建带空格文件名的文件时有些问题,同时我添加了随机命名以避免被覆盖。

我在这里找到了一种清理文件名中的空格的方法(如何将空格替换为下划线或反之?):

def urlify(self, s):
    # Remove all non-word characters (everything except numbers and letters)
    s = re.sub(r"[^\w\s]", '', s)
    # Replace all runs of whitespace with a single dash
    s = re.sub(r"\s+", '-', s)
    return s

那么

driver.save_screenshot('c:\\pytest_screenshots\\%s' % screen_name)

在哪里

def datetime_now(prefix):
    symbols = str(datetime.datetime.now())
    return prefix + "-" + "".join(symbols)

screen_name = self.urlify(datetime_now('screen')) + '.png'

5

这里有一个类似的问题,回答看起来更全面,我留下了来源:

如何在Python中使用Selenium WebDriver进行部分截图?

from selenium import webdriver
from PIL import Image
from io import BytesIO

fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')

# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
png = fox.get_screenshot_as_png() # saves screenshot of entire page
fox.quit()

im = Image.open(BytesIO(png)) # uses PIL library to open image in memory

left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']


im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image

3
你可以使用以下函数来处理相对路径,因为将绝对路径添加到脚本中并不是一个好主意。
导入
import sys, os

请使用以下代码:

使用以下代码:

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'Screenshots'+ os.sep)
driver.get_screenshot_as_file(screenshotpath+"testPngFunction.png")

请确保在.py文件所在的位置创建文件夹。 os.path.join还可以防止您在跨平台上运行脚本,例如UNIX和Windows。它将在运行时根据操作系统生成路径分隔符。os.sep类似于Java中的File.separator

2
TakeScreenShot screenshot=new TakeScreenShot();
screenshot.screenShot("screenshots//TestScreenshot//password.png");

it will work , please try.


0
请查看下面的Python脚本,使用Chrome Web驱动程序的selenium包来拍摄FB首页。
脚本:
import selenium

from selenium import webdriver

import time

from time import sleep

chrome_browser = webdriver.Chrome()

chrome_browser.get('https://www.facebook.com/') # Enter to FB login page

sleep(5)

chrome_browser.save_screenshot('C:/Users/user/Desktop/demo.png') # To take FB homepage snap

chrome_browser.close() # To Close the driver connection

chrome_browser.quit() # To Close the browser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接