首页 > 解决方案 > 打印屏幕循环

问题描述

需要一些帮助。我得到了这个 python 代码来加载 url 并进行屏幕打印。

我需要实现这一点:

  1. 而不是数组,从文本文件中读取 url
  2. 获取加载的每个 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...")

标签: pythonpython-3.xseleniumloopsscreenshot

解决方案


将 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...")

输出

思科网

google.com

修改细节

  • links.txt从文本文件中读取 URL 。
  • 修剪文件的每一行。
  • 解析每个 URL 并将主机名用作屏幕截图的文件名。urlparse(url).hostname返回有效 URL 的主机名。

参考


推荐阅读