본문 바로가기
개발기록/python

[python] selenium에서 iframe 제어

by spectrum20 2024. 9. 21.

selenium에서 iframe 제어하기

find_element() 코드에서 해당 요소가 있는데도 'no such element' 라는 에러가 뜨면서 해당 요소를 못 찾을 때

iframe 때문인 경우가 많은데, iframe 안에 있는 요소는 해당 iframe으로 이동한 후, 요소를 찾아줘야 한다

 

 

iframe 이동하기

- id로 iframe 이동하기

driver.switch_to.frame(' iframe id ')

 

- index로 iframe 이동하기

driver.switch_to.frame(0)
driver.switch_to.frame(1)
driver.switch_to.frame(2)

 

iframe 나오기

iframe을 이동한 후에 다시 처음 html로 돌아가기

driver.switch_to.default_content()

 

 

 

 

- default content에서 iframe1에 있는 요소를 찾을 때는 switch_to.frame('iframe1')로 이동

- iframe1에서 기존 html의 요소를 찾을 때는 switch_to.defualt content()로 이동

- ifrmae1에서 iframe2에 있는 요소를 찾을 때는, switch_to.default content()로 돌아온 후, switch_to.frame('iframe2')로 이동

 

 


# alert 창 제어하기

driver.switch_to.alert

# 알림창 수락
driver.switch_to.alert.accept()

# 알림창 거절
driver.switch_to.alert.dismiss()

# 알림창 텍스트 가져오기
driver.switch_to.alert.text

# 알림창 문자 보내기
driver.switch_to.alert.send_keys('  ')

 

 

+ 추가

from selenium.webdriver.common.alert import Alert

# 알림창 수락
Alert(driver).accept() 

# 알림창 거절
Alert(driver).dismiss() 

#알림창 텍스트 가져오기
print(Alert(driver).text
반응형

댓글