본문 바로가기
Python

[Python] Selnium 화면 캡쳐하기

by Guardy 2021. 2. 15.
728x90

selenium, 스크린샷, selenium 화면 저장, selenium png, selenium 캡쳐

이번글에서는 python selnium chrome 창에서 화면 스크린샷을 png로 저장하는 방법에 대해 알려드리려고 합니다.

우선 화면 캡쳐의 경우 headless 모드에서 정상 작동합니다. headless 옵션을 걸지 않을 경우, 해상도 문제로 정상적으로 저장되지 않는 현상이 있습니다.

따라서 driver 실행전 option을 이용해 headless 모드를 설정합니다.

[방식을 바꿔서 headless로 안해도됩니다.]

chrome_options = Options()
chrome_options.headless = True

그 다음 driver을 이용해 캡쳐하고 싶은 주소로 이동합니다.

url = "https://www.naver.com/"
drvier.get(url)

네이버에서 로그인한 부분을 가져오려고 합니다.

해당부분을 스크린샷 찍는 방법은 다음과 같습니다. 우선 find element를 이요해 해당 element를 가져옵니다.

네이버 로그인 부분은 sc_login class이기 때문에 다음과 같이 element를 가져올 수 있습니다.

element = driver.find_element_by_class_name("sc_login")

이제 해당 element를 screenshot_as_png라는 함수를 이용해서 image byte로 만들어줍니다.

element_png = element.screenshot_as_png

image byte를 file open을 이용하여 png로 저장해주면 끝입니다

with open('test.png', "wb") as file:
     file.write(element_png)

위 사진은 코드를 돌렸을때 저장되는 png 파일입니다. 전체 소스코드는 다음과 같습니다.

import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
#chrome_options.headless = True
chrome_options.add_argument('--profile-directory=Default')
chrome_options.add_argument("--incognito")
chrome_options.add_argument("--disable-plugins-discovery")
chrome_options.add_argument("--start-maximized")
driver = webdriver.Chrome(options=chrome_options)
url = "https://www.naver.com/"
driver.get(url)
element = driver.find_element_by_class_name("sc_login")
element_png = element.screenshot_as_png
with open('test.png', "wb") as file:
    file.write(element_png)

 

도움이 되셨다면 공감과 댓글 부탁드립니다. 긴 글 읽어주셔서 감사합니다.

728x90

'Python' 카테고리의 다른 글

[AWS S3] image python upload 코드  (0) 2020.09.10
쿠팡 Wing Login with python requests  (0) 2020.07.23