2024/04/05 5

[Selenium] Expected Conditions(EC)

파이썬에서 코드 동작을 멈추기 위해서 time.sleep()을 사용해도 되지만, 특정 조건을 만족할 때까지 정지하도록 하는 코드를 사용할 수 있다 from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome(options=chrome_options) WebDriverWait(driver, 5).until( EC.element_to_be_clickable((By.XPATH, f'{xpath}')) ) 사용은 위와 같이 하면 된다 위 예시에서는 해당 element가 클릭 가능한 상태가 될 때까지 최대 5초간 기다린다 5초가 지나기 전에 조건을 만족하면 진행되고, 5초가 지나도 조건을 만족하지 못하면 에러가 ..

Programing/Python 2024.04.05

[Selenium] 드롭다운 메뉴 선택하기

from selenium.webdriver.support.select import Select dropdown_element = driver.find_element(By.XPATH, f'{xpath}') dropdown_select = Select(dropdown_element) dropdown_select.select_by_value("1") selenium의 Select를 이용해서 드롭다운 메뉴를 선택할 수 있다 dropdown_select.select_by_value("1") dropdown_select.select_by_index(1) dropdown_select.select_by_visible_text('옵션3') 여러 방법으로 드롭다운 메뉴 중 하나를 선택할 수 있다

Programing/Python 2024.04.05

[Selenium] iframe

웹 페이지를 탐색하다 보면 분명 xpath 등을 그대로 복사해왔는데도 요소가 찾아지질 않는 문제가 발생하기도 한다 이는 iframe(inline frame, 페이지 속의 페이지) 때문이고, 해결하기 위해서는 해당 요소가 들어있는 iframe으로 이동한 뒤에 해당 요소를 찾아주어야 한다 ifrm = driver.find_element(By.CSS_SELECTOR, '#ifrm') driver.switch_to.frame(ifrm) iframe도 다른 html 요소들과 마찬가지로 selector나 xpath등이 존재하기 때문에 이를 이용하여 찾아주고, switch_to.frame() 함수를 이용해서 이동해 주면 된다 만약 iframe 안에 있는 iframe으로 이동하기 위해서는 위 과정을 두 번 거쳐 주면 ..

Programing/Python 2024.04.05

[Selenium] handle

셀레니움을 통해 웹페이지를 탐색하다 새로운 창이 뜨더라도 기존 창에서만 조작이 가능하고, 새로운 창의 요소에 대해서는 접근을 하지 못한다 따라서 handle을 변경하여 새로운 창에서도 요소들을 가져올 수 있게 해보겠다 main_window = driver.current_window_handle 이렇게 현재 창을 가져올 수 있다 for handle in driver.window_handles: if handle != main_window: driver.switch_to.window(handle) break 전체 창은 driver.window_handles로 가져올 수 있고, switch_to.window() 함수를 이용해 handle을 변경할 수 있다 main_window가 아닌 window_handle은..

Programing/Python 2024.04.05

[Selenium] 파이썬으로 Chrome 조작하기

터미널에서 pip install selenium으로 셀레니움을 설치해준다 (* selenium 4 이상부터는 크롬 드라이브 설치가 필요 없다) import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys 임포트 해 주고 chrome_options = Options() chrome_options.add_experimental_option("detach", True) 크롬 창이 자동으로 꺼지지 않게 옵션을 설정해 준다 driver = ..

Programing/Python 2024.04.05