Element 회득
# 해당 모듈에 find_element에 사용할 키 스트링이 정의되어있음
from selenium.webdriver.common.by import By
# 드라이버 획득
# ...
# 클래스 이름으로 Element 획득
element1 = driver.find_element(By.CLASS_NAME, "gLFyf")
# xpath로 Element 획득
element2 = driver.find_element(By.XPATH, "/html/body/div[1]/div[3]/form/div[1]/div[1]/div[4]/center/input[1]")
XPath(XML Path Language)는 XML문서 상의 경로를 표현한다
CLASS_NAME이 중복되는 경우 find_element(By.CLASS_NAME, ...)을 통해 얻어오면 첫번째 Element를 가져오기 때문에 원하는 Element가 두번째 있는경우 정상적으로 받아올수 없다
구글 페이지에 들어갔을때 검색 버튼의 클래스가 "gNO89b" 인데 해당 클래스 가 2개 존재하기 때문에 XPath를 통해서 얻어와야 원하는 Element를 얻을수 있다
# 구글 검색 페이지
# 찾기 버튼을 클래스로 얻어왔을때
find_element_list = driver.find_elements(By.CLASS_NAME, "gNO89b")
list_count = len(find_element_list)
print("리스트 카운트 -{cnt}".format(cnt=list_count)) # 2개가 출력된다
Element에 키 입력
# 얻어온 엘리멘트에 스트링을 설정
input_element.send_keys("페페")
# 기능키(enter/end ...) 입력
# from selenium.webdriver import Keys 해야함
input_element.send_keys(Keys.ENTER)
Element 클릭 처리
search_element.click()
Element 자식 노드들 접근
""" google.com의 body의 자식 element 접근 """
# body element를 얻는다
body_element = driver.find_element(By.TAG_NAME, 'body')
# body_element의 자식 노드들을 얻는다
child_elements = body_element.find_elements(By.XPATH, './child::*')
# 자신 카운트를 얻는다
print("num:{COUNT}".format(COUNT=len(child_elements)))'라이브러리 > Selenium' 카테고리의 다른 글
| [Selenium] 스크롤 (0) | 2024.09.18 |
|---|---|
| [Selenium] Python에서 대기 방법 (1) | 2024.09.18 |
| [Selenium] Element 클릭 처리 (1) | 2024.09.17 |
| [Selenium] WebDriver (0) | 2024.08.31 |
| [Selenium] 기본 (1) | 2024.08.30 |