본문으로 바로가기

[Selenium] Web Console Log 출력

category selenium 2020. 1. 7. 20:45
728x90

1. 로그를 받도록 설정

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


d = DesiredCapabilities.CHROME
#log 종류는 OFF, SEVERE, WARNING, INFO, DEBUG, ALL 존재
d['goog:loggingPrefs'] = { 'browser' : 'SEVERE' }
driver = webdriver.Chrome(desired_capabilities=d)

driver.implicitly_wait(3)
driver.set_window_size(1920, 1080)
driver.get("http://www.naver.com/")

2. 로그 출력 및 저장

import inspect
import os
import json
from selenium import webdriver

#Console log 저장 파일 이름을 해당 함수를  호출한 파일의 이름으로 생성하기 위함
Path=os.path.basename(inspect.getfile(inspect.currentframe()))
#파일 중 확장자를 제거한 이름을 확보하기 위함
filename=Path.split('.')

def console_logfile(driver, filename):

    OUTPUT_FILE_NAME = filename[0] + '.log'

    #저장할 파일 생성
    open_output_file = open(OUTPUT_FILE_NAME, 'w')

    logfile=0
    for entry in driver.get_log('browser'):
        # 파일에 쓸 내용
        print(entry)
        #entry의 경우 dict type이라 str type인 json 형식으로 변형 필요
        open_output_file.write(json.dumps(entry))
        open_output_file.write('\n')
        logfile=logfile+1
    # 파일 닫음
    open_output_file.close()
    #파일이 Empty일 경우 삭제
    if logfile==0:
        os.remove(OUTPUT_FILE_NAME)