首页 > 解决方案 > Selenium - 不同名称的屏幕截图

问题描述

我正在使用 Selenium 从 url 列表中获取屏幕截图。test.txt 包括 reddit.com、stackoverflow.com 和 spotify.com。遍历此列表时,我希望它保存在文件夹 Screenshots 中,文件名为 url + '.png'。但它不起作用。我要么得到错误,要么它只是继续运行而不做任何事情。这个有效,但它只是覆盖了旧的

screenshot = driver.save_screenshot('Screenshots/foo.png')

我希望它看起来像这样,但它不起作用:

screenshot = driver.save_screenshot('Screenshots/', line,  '.png')

我是 python 新手,但使用 + 而不是 ' 也不起作用。问题是它需要太多的论点。

class Screenshot():

filehandle = open("test.txt", "r")
for line in filehandle:
    DRIVER = 'chromedriver'
    driver = webdriver.Chrome(DRIVER)
    driver.get(line)

    screenshot = driver.save_screenshot('Screenshots/foo.png')
    driver.quit()

标签: python

解决方案


对于像这样的简单任务,不需要创建屏幕截图类。

#!/usr/bin/env python
from __future__ import print_function

import os
from selenium import webdriver


def main():
    driver = webdriver.Chrome()

    # With automatically closes files when they go out of scope
    with open('test.txt', 'r') as f:
        for url in f.readlines():
            driver.get(url)

            # os.path.join should make it platform agnostic
            # Also remove any '/' from the url and replace to avoid any file system save issues
            sn_name = os.path.join('Screenshots', url.strip().replace('/', '-') + '.png')
            print('Attempting to save:', sn_name)

            # '.save_screenshot' returns false if it fails so throw exception
            if not driver.save_screenshot(sn_name):
                raise Exception('Could not save screen shot: ' + sn_name)

    # Close browser
    driver.quit()


if __name__ == '__main__':
    main()

推荐阅读