Selenium Library
Selenium 라이브러리
- Web Browser를 컨트롤하여 Web UI에 대한 조작을 자동화하는 프로그램을 구현하는데
용이한 도구를 제공하는 라이브러리이다.
* Selenium Official Documentation (URL)
Installation (설치)
Installation Command (설치 명령어) (URL)
# Installation of Selenium libraries for Python can be done using pip
pip install selenium
# Installation of Selenium libraries for Python can be done using anaconda
conda install selenium
Installing Selenium Driver (Selenium 드라이버 설치) (URL)
Browser | Supported OS | Maintained By | Download URL | Issue Tracker URL |
Chromium/Chrome | Windows/macOS/Linux | Downloads | Issues | |
Firefox | Windows/macOS/Linux | Mozilla | Downloads | Issues |
Edge | Windows/macOS | Microsoft | Downloads | Issues |
Internet Explorer (Deprecated) |
Windows | Selenium Project | Downloads | Issues |
Safari | macOS High Sierra and Newer |
Apple | Built in the OS | Issues |
- 셀레늄 라이브러리를 이용하기 위해서는 사용하는 인터넷 브라우저별 Selenium Driver를 설치해야 한다.
- 설치 후, 해당 드라이버의 경로를 실행 PATH에 넣어 준다.
(개발중인 파이썬 파일과 동일한 디렉토리에 드라이버 exe파일을 위치시킨다.)
Import (모듈 임포트)
# Recommended import style
from selenium import webdriver
# Special keys class
from selenium.webdriver.common.keys import Keys
# Exception classes
from selenium.common.exceptions import <Exception-Class-Name>
Selenium Classes in Python (Selenium 클래스)
webdriver.Firefox
webdriver.FirefoxProfile
webdriver.Chrome
webdriver.ChromeOptions
webdriver.Ie
webdriver.Opera
webdriver.PhantomJS
webdriver.Remote
webdriver.DesiredCapabilities
webdriver.ActionChains
webdriver.TouchActions
webdriver.Proxy
Open and Close a Browser with Selenium (브라우저 실행)
# Chrome
options = ChromeOptions()
driver = webdriver.Chrome(options=option)
# Edge
options = EdgeOptions()
driver = webdriver.Edge(options=option)
# Firefox
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
# Safari
driver = webdriver.Safari()
# Closing
driver.quit()
Selenium Property (Selenium 속성)
Basis
from selenium import webdriver
# Chrome
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
# Edge
options = EdgeOptions()
driver = webdriver.Edge(options=options)
# Firefox
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
# Safari
driver = webdriver.Safari()
Properties (Summary)
Category | Property | Description |
Current Information | current_url | Gets the URL of the current page. |
current_window_handle | Returns the handle of the current window. | |
page_source | Gets the source of the current page. | |
title | Returns the title of the current page. |
Selenium Methods (Selenium 메소드)
Basis
from selenium import webdriver
# Chrome
options = ChromeOptions()
driver = webdriver.Chrome(options=options)
# Edge
options = EdgeOptions()
driver = webdriver.Edge(options=options)
# Firefox
options = FirefoxOptions()
driver = webdriver.Firefox(options=options)
# Safari
driver = webdriver.Safari()
Methods (Summary)
Category | Method | Description |
Basic Operation | forward() | Goes one step forward in the browser history. |
back() | Goes one step backward in the browser history. | |
refresh() | Refreshes the current page. | |
close() | Closes the current window. | |
quit() | Quits the driver and closes every associated window. | |
create_web_element() | Creates a web element with the specified element_id. | |
implicitly_wait() | Sets a sticky timeout to implicitly wait for an element to be found. | |
set_page_load_timeout() | Set the amount of time to wait for a page load to complete before throwing an error. | |
Element Searching | find_element() | - for Selenium Version 4 |
find_element_by_name() | - for Selenium Version 3 | |
find_element_by_tag_name() | - for Selenium Version 3 | |
find_element_by_class_name() | - for Selenium Version 3 | |
find_element_by_id() | - for Selenium Version 3 | |
find_element_by_link_text() | - for Selenium Version 3 | |
find_element_by_partial_link_text() | - for Selenium Version 3 | |
find_element_by_css_selector() | - for Selenium Version 3 | |
find_element_by_xpath() | - for Selenium Version 3 | |
find_elements() | - for Selenium Version 4 | |
find_elements_by_name() | - for Selenium Version 3 | |
find_elements_by_tag_name() | - for Selenium Version 3 | |
find_elements_by_class_name() | - for Selenium Version 3 | |
find_elements_by_id() | - for Selenium Version 3 | |
find_elements_by_link_text() | - for Selenium Version 3 | |
find_elements_by_partial_link_text() | - for Selenium Version 3 | |
find_elements_by_css_selector() | - for Selenium Version 3 | |
find_elements_by_xpath() | - for Selenium Version 3 | |
Window Operation | get_window_position() | Gets the x, y position of the current window. |
get_window_rect() | Gets the x, y coordinates of the window as well as height and width of the current window. | |
get_window_size() | Gets the width and height of the current window. | |
fullscreen_window() | Invokes the window manager-specific ‘full screen’ operation | |
maximize_window() | Maximizes the current window that webdriver is using | |
minimize_window() | Invokes the window manager-specific ‘minimize’ operation | |
set_window_position() | Sets the x, y position of the current window. (window.moveTo) | |
set_window_rect() | Sets the x, y coordinates of the window as well as height and width of the current window. | |
JavaScript Operation | execute_script() | Synchronously Executes JavaScript in the current window/frame. |
execute_async_script() | Asynchronously Executes JavaScript in the current window/frame. | |
set_script_timeout() | Set the amount of time that the script should wait during an execute_async_script call before throwing an error. | |
Screenshot | get_screenshot_as_base64() | Gets the screenshot of the current window as a base64 encoded string which is useful in embedded images in HTML. |
get_screenshot_as_png() | Saves a screenshot of the current window to a PNG image file. | |
get_screenshot_as_file() | Gets the screenshot of the current window as a binary data. | |
Cookie Management | get_cookie() | Get a single cookie by name. Returns the cookie if found, None if not. |
get_cookies() | Returns a set of dictionaries, corresponding to cookies visible in the current session. | |
add_cookie() | Adds a cookie to your current session. | |
delete_cookie() | Deletes a single cookie with the given name. | |
delete_all_cookies() | Delete all cookies in the scope of the session. | |
Log Management | get_log() | Gets the log for a given log type |
Methods (Details, Signatures)
# Basic Operation
forward() -> None
back() -> None
refresh() -> None
close() -> None
quit() -> None
create_web_element(
element_id: Any
) -> WebElement
implicitly_wait(
time_to_wait: Any
) -> None
set_page_load_timeout(
time_to_wait: Any
) -> None
# Element Searching
find_element(
by: ... = ...,
value: Any | None = ...
) -> WebElement
find_element_by_name(
name: Any
) -> WebElement
find_element_by_tag_name(
name: Any
) -> WebElement
find_element_by_class_name(
name: Any
) -> WebElement
find_element_by_id(
id_: Any
) -> WebElement
find_element_by_link_text(
link_text: Any
) -> WebElement
find_element_by_partial_link_text(
link_text: Any
) -> WebElement
find_element_by_css_selector(
css_selector: Any
) -> WebElement
find_element_by_xpath(
xpath: Any
) -> WebElement
find_elements(
by: ... = ...,
value: Any | None = ...
) -> list[WebElement]
find_elements_by_name(
name: Any
) -> list[WebElement]
find_elements_by_tag_name(
name: Any
) -> list[WebElement]
find_elements_by_class_name(
name: Any
) -> list[WebElement]
find_elements_by_id(
id_: Any
) -> list[WebElement]
find_elements_by_link_text(
link_text: Any
) -> list[WebElement]
find_elements_by_partial_link_text(
link_text: Any
) -> list[WebElement]
find_elements_by_css_selector(
css_selector: Any
) -> list[WebElement]
find_elements_by_xpath(
xpath: Any
) -> list[WebElement]
# Window Operation
get_window_position(
windowHandle: str = ...
) -> Any
get_window_rect() -> Any
get_window_size(
windowHandle: str = ...
) -> Any
fullscreen_window() -> None
maximize_window() -> None
minimize_window() -> None
set_window_position(
x: Any,
y: Any,
windowHandle: str = ...
) -> Any
set_window_rect(
x: Any | None = ...,
y: Any | None = ...,
width: Any | None = ...,
height: Any | None = ...
) -> Any
# JavaScript Operation
execute_script(
script: Any,
*args: Any
) -> Any
execute_async_script(
script: Any,
*args: Any
) -> Any
set_script_timeout(
time_to_wait: Any
) -> None
# Screenshot
get_screenshot_as_base64() -> str
get_screenshot_as_png() -> bytes
get_screenshot_as_file(
filename: Any
) -> bool
# Cookie Management
get_cookie(
name: Any
) -> Any
get_cookies() -> Any
add_cookie(
cookie_dict: Any
) -> None
delete_cookie(
name: Any
) -> None
delete_all_cookies() -> None
# Log Management
get_log(
log_type: Any
) -> Any
Selenium Exception Classes (Selenium 예외 클래스)
- 별의별 예외사항이 생기는 웹 환경이니 만큼,
셀레늄 라이브러리를 사용할 때 예외 클래스를 숙지해놓는 것이 여러모로 이로울 것이라 생각된다.
Import (예외 클래스 임포트)
# Exception classes
from selenium.common.exceptions import <Exception-Class-Name>
- <Exception-Class-Name> 에 대입할 예외 클래스 이름은 하단 테이블의 Exception Class Name을 참고하자.
Selenium Exception Classes
Base Class | Exception Class Name | Description |
Exception | WebDriverException | - webdriver exception의 Base Class이다. |
WebDriverException |
ElementClickInterceptedException | - 클릭할 Element가 모호하여 Element Click 명령을 수행할 수 없을 때 발생되는 예외이다. |
ImeActivationFailedException | - IME 엔진 구동에 실패했을 때 발생되는 예외이다. |
|
ImeNotAvailableException | - IME support가 이용 불가능할 때 발생되는 예외이다. - 해당 머신에서 IME support가 이용 불가능하면 IME에 관련된 모든 Method에서 이 예외가 발생할 수있다. |
|
InsecureCertificateException | - User Agent가 웹 탐색 중, 인증서 경고를 맞닥뜨렸을 때 발생되는 예외이다. - 이는 주로 인증서가 만료되었거나, TLS 인증서가 유효하지 않을 때 발생된다. |
|
InvalidArgumentException | - 유효하지 않은 Argument가 전달되었을 때 발생되는 예외이다. |
|
InvalidCookieDomainException | - 현재 URL에서 다른 도메인에 쿠키를 추가하려 시도했을 때 발생되는 예외이다. |
|
InvalidCoordinatesException |
- 유효하지 않은 Interaction Operation에 대한 Corrdinate가 제공됐을 때 발생되는 예외이다. |
|
InvalidElementStateException |
- Element가 유효하지 않은 상태에 있을 때 발생되는 예외이다. - 주로, Editable하지 않은, Resettable하지 않은 Element의 내용에 Clear()를 시도할 때 발생되는 예외이다. |
|
InvalidSelectorException |
- Selector가 Element를 찾는 과정에서 WebElement를 반환할 수 없을 때 발생되는 예외이다. - 현재는 xpath Expression으로 구성된 Selector의 Syntax가 유효하지 않거나 WebElement를 적절히 지정하고 있지 않을 때 예외를 발생시킨다. |
|
InvalidSessionIdException |
- 주어진 Session ID가 Active Session 리스트에 존재하지 않을 때 발생되는 예외이다. - Session이 존재하지 않거나, Active 상태에 있지 않을 때 발생되는 예외이다. |
|
InvalidSwitchToTargetException |
- Switch될 Frame 혹은 Window가 존재하지 않을 때 발생되는 예외이다. |
|
JavascriptException |
- 실행중인 JavaScript 코드에 오류가 생긴 경우 발생되는 예외이다. |
|
MoveTargetOutOfBoundsException |
- Out of Document와 같이, Target에 대한 ActionsChains의 move() 메서드가 유효하지 않을 경우 발생되는 예외이다. |
|
NoAlertPresentException |
- 표현되지 않은 경고창으로 전환될 때 발생되는 예외이다. - 이는 화면에 경고창이 띄어지지 않은 상태에서 Alert() 클래스의 Operation이 수행될 때 발생될 수 있는 예외이다. |
|
NoSuchAttributeException |
- Element의 해당 Attribute가 발견되지 않을 때 발생되는 예외이다. - Element에 해당 Attribute가 존재하는지를 테스트하고자 할 때 이 예외를 이용할 수 있다. - 브라우저별로 Property Name이 다를 수 있음에 유의해야 한다. |
|
NoSuchCookieException |
No cookie matching the given path name was found amongst the associated cookies of the current browsing context’s active document. | |
NoSuchElementException |
Thrown when element could not be found. If you encounter this exception, you may want to check the following:
|
|
NoSuchShadowRootException |
Thrown when trying to access the shadow root of an element when it does not have a shadow root attached. | |
RemoteDriverServerException |
||
ScreenshotException |
A screen capture was made impossible. | |
SessionNotCreatedException |
A new session could not be created. | |
StaleElementReferenceException |
Thrown when a reference to an element is now “stale”. Stale means the element no longer appears on the DOM of the page. Possible causes of StaleElementReferenceException include, but not limited to:
|
|
TimeoutException |
Thrown when a command does not complete in enough time. | |
UnableToSetCookieException |
Thrown when a driver fails to set a cookie. | |
UnexpectedAlertPresentException |
Thrown when an unexpected alert has appeared. Usually raised when an unexpected modal is blocking the webdriver from executing commands. |
|
UnexpectedTagNameException |
Thrown when a support class did not get an expected web element. | |
UnknownMethodException |
The requested command matched a known URL but did not match any methods for that URL. | |
InvalidElementStateException |
ElementNotInteractableException | Thrown when an element is present in the DOM but interactions with that element will hit another element due to paint order |
ElementNotSelectableException | Thrown when trying to select an unselectable element. For example, selecting a ‘script’ element. |
|
ElementNotVisibleException | Thrown when an element is present on the DOM, but it is not visible, and so is not able to be interacted with. Most commonly encountered when trying to click or read text of an element that is hidden from view. |
|
InvalidSwitchToTargetException |
NoSuchFrameException | Thrown when frame target to be switched doesn’t exist. |
NoSuchWindowException | Thrown when window target to be switched doesn’t exist. To find the current set of active window handles, you can get a list of the active window handles in the following way: print(driver.window_handles) |
Selenium Exception Class Signatures
# Derived Classes of "Exception" Class
selenium.common.exceptions.WebDriverException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
# Derived Classes of "WebDriverException" Class
selenium.common.exceptions.ElementClickInterceptedException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.ImeActivationFailedException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.ImeNotAvailableException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.InsecureCertificateException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.InvalidArgumentException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.InvalidCookieDomainException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.InvalidCoordinatesException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.InvalidElementStateException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.InvalidSelectorException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.InvalidSessionIdException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.InvalidSwitchToTargetException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.JavascriptException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.MoveTargetOutOfBoundsException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.NoAlertPresentException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.NoSuchAttributeException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.NoSuchCookieException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.NoSuchElementException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.NoSuchShadowRootException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.RemoteDriverServerException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.ScreenshotException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.SessionNotCreatedException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.StaleElementReferenceException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.TimeoutException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.UnableToSetCookieException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.UnexpectedAlertPresentException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None,
alert_text: Optional[str] = None)
selenium.common.exceptions.UnexpectedTagNameException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.UnknownMethodException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
# Derived Classes of "InvalidElementStateException" Class
selenium.common.exceptions.ElementNotInteractableException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.ElementNotSelectableException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.ElementNotVisibleException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
# Derived Classes of "InvalidSwitchToTargetException" Class
selenium.common.exceptions.NoSuchFrameException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
selenium.common.exceptions.NoSuchWindowException(
msg: Optional[str] = None,
screen: Optional[str] = None,
stacktrace: Optional[Sequence[str]] = None)
Reference: "Selenium with Python", Read the Docs, 2022.08.11 검색, URL.
Reference: "Selenium Documentation", Selenium.dev, 2022.08.11 검색, URL.
Reference: "Selenium Documentation", Selenium.dev, 2022.08.11 검색, URL.
Reference: "Selenium Webdriver Tutorial", tutorialspoint, 2022.08.14 검색, URL.