python - 打印屏幕循环
问题描述
需要一些帮助。我得到了这个 python 代码来加载 url 并进行屏幕打印。
我需要实现这一点:
- 而不是数组,从文本文件中读取 url
- 获取加载的每个 url 的屏幕打印并保存。使用代码,屏幕打印被覆盖
from selenium import webdriver
from time import sleep
driver = webdriver.Firefox()
url = ["http://google.com", "http://cisco.com"]
for element in url:
driver.get(element)
driver.get_screenshot_as_file("screenshot.png")
sleep(2)
driver.quit()
print("end...")
解决方案
将 URL 存储在文本文件中,然后逐行读取。然后使用带有 URL 主机名的文件名截取屏幕截图。
我已经修改了您的代码,并且可以将每个 url 的屏幕截图存储在单独的文件中。我用过 Python 3.6.9。
目录结构:
.
├── links.txt
├── requirements.txt
└── screenshots_of_links.py
links.txt
:
http://google.com
http://cisco.com
requirements.txt
:
selenium==3.141.0
urllib3==1.25.10
screenshots_of_links.py
:
from selenium import webdriver
from urllib.parse import urlparse
from time import sleep
driver = webdriver.Firefox()
with open("links.txt") as url_file:
for line in url_file.readlines():
url = line.strip()
if url != "":
driver.get(url)
host = urlparse(url).hostname
driver.get_screenshot_as_file("{}.png".format(host))
sleep(2)
driver.quit()
print("end...")
输出:
修改细节:
links.txt
从文本文件中读取 URL 。- 修剪文件的每一行。
- 解析每个 URL 并将主机名用作屏幕截图的文件名。
urlparse(url).hostname
返回有效 URL 的主机名。
参考:
推荐阅读
- python-3.x - 如何以这种方式排序列表:[1, 2, 1, 2, 1, 2]
- ionic-framework - 如何使用 Xcode 模拟器使用 Cordova 离子项目重新加载
- javascript - Bootstrap4 验证在 IE 11 中不起作用
- jquery - 我无法在编辑模式中显示图像
- kubernetes - kubernetes ssh 连接到 pod
- reactjs - 如何在 Windows 上运行这个 docker 命令?
- node.js - Nodejs如何使请求对象在所有文件中全局可用
- django - 表单布尔字段未出现在 request.POST 数据中
- c++ - 使用指针读取和写入文件
- excel - 无法设置 Borders 类的 Weight 属性