Grundsätzlich gibt es viele verschiedene Möglichkeiten innerhalb von Python basierten Selenium Test Screenhots und Videos auszuwerten. Ich nutzte dieses Verfahren innerhalb meiner Unittest, und speichere diese nach der Prüfung innerhalb einer Jenkins Pipeline, entsprechend in Xray ab. Das Verfahren werde ich aber in einem anderen Beitrag genauer beschreiben.
Screenshots mit Python erstellen
Wir starten einen Web-Treiber (Chromium) und öffnen die Webseite python.org.
from selenium import webdriver driver = webdriver.Chrome() driver.get('https://python.org')
Dann rufen wir die Methode auf:
driver.save_screenshot("screenshot.png")
Der Screenshot wird im gleichen Verzeichnis wie das Programm gespeichert: dem Programmpfad.
Der vollständige Code ist unten dargestellt. Da ich jetzt mit dem Chrom-Browser getestet habe, enthält er die ChromeOptions als Parameter.
from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument("--test-type") options.binary_location = "/usr/bin/chromium" driver = webdriver.Chrome(chrome_options=options) driver.get('https://python.org') driver.save_screenshot("screenshot.png") driver.close()
Screenshot von einem html-Element erstellen
Ihr könnt einen Screenshot von einem html-Element machen. Dies funktioniert so, dass Sie zuerst einen Screenshot der gesamten Seite machen und ihn dann auf die Größe des html-Elements zuschneiden.
Beispiel 1:
from selenium import webdriver from PIL import Image # take screenshot driver = webdriver.Chrome(); driver.get('https://www.google.com'); element = driver.find_element_by_id("hplogo"); location = element.location; size = element.size; driver.save_screenshot("pageImage.png"); # crop image x = location['x']; y = location['y']; width = location['x']+size['width']; height = location['y']+size['height']; im = Image.open('pageImage.png') im = im.crop((int(x), int(y), int(width), int(height))) im.save('element.png') driver.quit()
Beispiel 2:
#coding=utf-8 import time from selenium import webdriver from selenium.webdriver.chrome.options import Options def test_fullpage_screenshot(self): chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--start-maximized') driver = webdriver.Chrome(chrome_options=chrome_options) driver.get("yoururlxxx") time.sleep(2) #the element with longest height on page ele=driver.find_element("xpath", '//div[@class="react-grid-layout layout"]') total_height = ele.size["height"]+1000 driver.set_window_size(1920, total_height) #the trick time.sleep(2) driver.save_screenshot("screenshot1.png") driver.quit() if __name__ == "__main__": test_fullpage_screenshot()
Screenshot der kompletten Seite mit Selenium Python und Chromedriver machen
Es gibt viele Möglichkeiten dieses Problem mit Python und Selenium zu lösen.
Beispiel 1:
#coding=utf-8 import time from selenium import webdriver from selenium.webdriver.chrome.options import Options def test_fullpage_screenshot(self): chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--start-maximized') driver = webdriver.Chrome(chrome_options=chrome_options) driver.get("yoururlxxx") time.sleep(2) #the element with longest height on page ele=driver.find_element("xpath", '//div[@class="react-grid-layout layout"]') total_height = ele.size["height"]+1000 driver.set_window_size(1920, total_height) #the trick time.sleep(2) driver.save_screenshot("screenshot1.png") driver.quit() if __name__ == "__main__": test_fullpage_screenshot()
Beispiel 2:
from selenium import webdriver def save_screenshot(driver: webdriver.Chrome, path: str = '/tmp/screenshot.png') -> None: # Ref: https://stackoverflow.com/a/52572919/ original_size = driver.get_window_size() required_width = driver.execute_script('return document.body.parentNode.scrollWidth') required_height = driver.execute_script('return document.body.parentNode.scrollHeight') driver.set_window_size(required_width, required_height) # driver.save_screenshot(path) # has scrollbar driver.find_element_by_tag_name('body').screenshot(path) # avoids scrollbar driver.set_window_size(original_size['width'], original_size['height'])
Beispiel 3:
from selenium import webdriver url = 'https://stackoverflow.com/' path = '/path/to/save/in/scrape.png' driver = webdriver.Chrome() driver.get(url) el = driver.find_element_by_tag_name('body') el.screenshot(path) driver.quit()
Beispiel 4:
<meta http-equiv="content-type" content="text/html; charset=utf-8"><pre class="lang-py s-code-block hljs python">from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://developer.mozilla.org/')
element = driver.find_element_by_tag_name('body')
element_png = element.screenshot_as_png
with open("test2.png", "wb") as file:
file.write(element_png)
Beispiel 5:
import sys from selenium import webdriver import util import os import time from PIL import Image def fullpage_screenshot(driver, file): print("Starting chrome full page screenshot workaround ...") total_width = driver.execute_script("return document.body.offsetWidth") total_height = driver.execute_script("return document.body.parentNode.scrollHeight") viewport_width = driver.execute_script("return document.body.clientWidth") viewport_height = driver.execute_script("return window.innerHeight") print("Total: ({0}, {1}), Viewport: ({2},{3})".format(total_width, total_height,viewport_width,viewport_height)) rectangles = [] i = 0 while i < total_height: ii = 0 top_height = i + viewport_height if top_height > total_height: top_height = total_height while ii < total_width: top_width = ii + viewport_width if top_width > total_width: top_width = total_width print("Appending rectangle ({0},{1},{2},{3})".format(ii, i, top_width, top_height)) rectangles.append((ii, i, top_width,top_height)) ii = ii + viewport_width i = i + viewport_height stitched_image = Image.new('RGB', (total_width, total_height)) previous = None part = 0 for rectangle in rectangles: if not previous is None: driver.execute_script("window.scrollTo({0}, {1})".format(rectangle[0], rectangle[1])) time.sleep(0.2) driver.execute_script("document.getElementById('topnav').setAttribute('style', 'position: absolute; top: 0px;');") time.sleep(0.2) print("Scrolled To ({0},{1})".format(rectangle[0], rectangle[1])) time.sleep(0.2) file_name = "part_{0}.png".format(part) print("Capturing {0} ...".format(file_name)) driver.get_screenshot_as_file(file_name) screenshot = Image.open(file_name) if rectangle[1] + viewport_height > total_height: offset = (rectangle[0], total_height - viewport_height) else: offset = (rectangle[0], rectangle[1]) print("Adding to stitched image with offset ({0}, {1})".format(offset[0],offset[1])) stitched_image.paste(screenshot, offset) del screenshot os.remove(file_name) part = part + 1 previous = rectangle stitched_image.save(file) print("Finishing chrome full page screenshot workaround...") return True driver = webdriver.Chrome() ''' Generate document-height screenshot ''' url = "http://effbot.org/imagingbook/introduction.htm" url = "http://www.w3schools.com/js/default.asp" driver.get(url) fullpage_screenshot(driver, "test1236.png")
Beispiel 6:
URL = 'http://www.w3schools.com/js/default.asp' options = webdriver.ChromeOptions() options.headless = True driver = webdriver.Chrome(options=options) driver.get(URL) S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X) driver.set_window_size(S('Width'),S('Height')) # May need manual adjustment driver.find_element_by_tag_name('body').screenshot('web_screenshot.png') driver.quit()
Neueste Kommentare