본문 바로가기
Python/Selenium

Selenium CookieNotFoundException 오류 해결하기

by PySun 2025. 2. 22.
반응형

소개

Selenium을 사용하여 웹 자동화를 구현할 때, 'CookieNotFoundException' 오류가 발생하는 경우가 있습니다. 이 오류는 특정 쿠키 정보를 찾으려고 할 때 발생하며, 일반적으로 쿠키가 존재하지 않거나 초기화되지 않았음을 나타냅니다. 이 블로그 글에서는 이러한 오류가 발생하는 원인과 해결 방법에 대해 알아보겠습니다.

에러 발생 예시 코드

먼저, 'CookieNotFoundException' 오류가 발생할 수 있는 간단한 예시 코드를 살펴봅시다.

from selenium import webdriver
from selenium.common.exceptions import CookieNotFoundException

# Chrome 드라이버 초기화
driver = webdriver.Chrome()

# 특정 웹사이트 열기
driver.get("https://example.com")

# 존재하지 않는 쿠키에 접근
try:
    cookie_value = driver.get_cookie("non_existing_cookie")  # 쿠키를 가져오려 할 때 오류 발생
except CookieNotFoundException as e:
    print(f"에러 발생: {e}")

에러 해결 방법

1. 쿠키가 설정되었는지 확인하기

문제의 원인은 쿠키가 존재하지 않을 때 발생합니다. 따라서 특정 쿠키가 설정되었는지 우선적으로 확인해야 합니다.

from selenium import webdriver

# Chrome 드라이버 초기화
driver = webdriver.Chrome()

# 특정 웹사이트 열기
driver.get("https://example.com")

# 현재 페이지의 모든 쿠키 확인
cookies = driver.get_cookies()
print("현재 쿠키 목록:", cookies)

# 특정 쿠키가 존재하는지 체크
cookie_name = "non_existing_cookie"
if any(cookie['name'] == cookie_name for cookie in cookies):
    cookie_value = driver.get_cookie(cookie_name)
    print(f"쿠키 값: {cookie_value['value']}")
else:
    print(f"{cookie_name} 쿠키가 존재하지 않습니다.")

2. 쿠키 설정하기

기존에 없던 쿠키를 사용해야 한다면, 직접 쿠키를 설정할 수 있습니다. 이 방법으로 오류를 피할 수 있습니다.

from selenium import webdriver

# Chrome 드라이버 초기화
driver = webdriver.Chrome()

# 특정 웹사이트 열기
driver.get("https://example.com")

# 쿠키 설정하기
driver.add_cookie({"name": "new_cookie", "value": "value123"})

# 쿠키 확인
cookie = driver.get_cookie("new_cookie")
print(f"설정된 쿠키 값: {cookie['value']}")

마무리

이 블로그 글에서는 Selenium을 사용할 때 발생하는 'CookieNotFoundException' 오류에 대한 해결 방법을 살펴보았습니다. 쿠키가 설정되었는지 확인하고, 필요하다면 쿠키를 직접 추가하여 이 문제를 해결할 수 있습니다. 웹 자동화를 수행할 때는 쿠키와 관련된 메서드 사용에 유의하여 오류를 예방하는 것이 중요합니다.

반응형