python - 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()
解决方案
对于像这样的简单任务,不需要创建屏幕截图类。
#!/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()
推荐阅读
- audio - Swift:命令中心不起作用,即使我明确设置按钮启用?
- c - OpenMP 并行化比顺序慢
- typescript - 打字稿:推断传递函数参数的类型
- javascript - 如何在 CSS 中向下移动剪贴蒙版?
- android - 将实时数据库 DatabaseReference.addListenerForSingleValueEvent 转换为云 Firestore
- firebase - Firebase 规则以设置特定属性的读/写
- mongodb - 在基于 Mongo 的 API 中搜索多个 ObjectId 的 HTTP 请求?
- php - 从服务器发送命令到 swift 应用程序
- reactjs - 从 dangerouslySetInnerHTML 延迟加载图像
- java - 如何使用 Jena 获取资源的 EXPLICIT listProperties(非推断属性)