경고창 (alert)
경고창이 떴을 때 수락 또는 거절을 눌러주거나 경고창의 텍스트를 가져올 수 있다.
# 경고창으로 이동
driver.switch_to.alert
from selenium.webdriver.common.alert import Alert
Alert(driver).accept() # 경고창 수락 누름
Alert(driver).dismiss() # 경고창 거절 누름
print(Alert(driver).text # 경고창 텍스트 얻음
쿠키값
# 쿠키값 얻기
driver.get_cookies()
# 쿠키 추가
driver.add_cookie()
# 쿠키 전부 삭제
driver.delete_all_cookies()
# 특정 쿠기 삭제
driver.delete_cookie(cookiename)
Wait till Load Webpage (로딩 대기)
브라우저에서 해당 웹 페이지의 요소들을 로드하는 데 시간이 걸린다. 따라서 element가 존재하지 않는다는 error를 보고 싶지 않다면 해당 요소가 전부 준비가 될 때까지 대기해야 한다.
# Implicit Waits (암묵적 대기)
driver.implicitly_wait(time_to_wait=5)
찾으려는 element가 로드될 때까지 지정한 시간만큼 대기할 수 있도록 설정한다. 이는 한 webdriver에 영구적으로 작용한다. 인자는 초 단위이며, Default 값은 0이다. 위의 예시는 5초까지 기다려 준다는 의미이다.
# Explicit Waits (명시적 대기)
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome('chromedriver')
driver.get(url='https://www.google.com/')
try:
element = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.CLASS_NAME , 'aaa'))
)
finally:
driver.quit()
간단하게는 time.sleep(secs) 함수를 사용하여 몇 초간 대기하는 방법이 있다. 웹페이지에서 class가 aaa인 어떤 element를 찾을 수 있는지를 최대 5초 동안 매 0.5초마다 시도한다. expected_conditions (EC)는 만약 element를 찾을 수 있었으면 True를, 아니라면 False를 반환한다.
제목이 어떤 문자열인지, 어떤 문자열을 포함하는지, 특정 또는 모든 요소가 로드되었거나의 여러 조건이 가능하다.
|
Custom으로 조건을 설정하는 것도 가능하다. __init__ 함수와 __call__ 함수를 구현한 class를 작성하면 된다.
until(method, message='') 함수는 method의 반환값이 False인 동안 계속 method를 실행한다. 반대로 until_not(method, message='') 함수는 True인 동안 실행한다.
클릭하기 (click)
클릭은 find_element 함수로 요소를 선택한 다음에, click() 함수를 호출한다.
# Ctrl + Shift + C을 누른 뒤 제목 부분을 클릭하고, Copy XPath를 이용하여 XPath를 얻음
posting = driver.find_element_by_xpath('//*[@id="rso"]/div[1]/div/div[1]/a/h3/span')
posting.click()
옵션 선택 및 제출 (submit)
select 내에서 인덱스로 선택하거나, 옵션의 텍스트, 혹은 어떤 값을 통해 선택이 가능하다.
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_name('select_name'))
select.select_by_index(index=2)
select.select_by_visible_text(text="option_text")
select.select_by_value(value='aa')
# 특정 해제
select.deselect_by_index(index=2)
select.deselect_by_visible_text(text="option_text")
select.deselect_by_value(value='고리오')
# 전부 해제
select.deselect_all()
# 제출
submit_btn.submit()
Drag and Drop
어떤 일련의 동작을 수행하기 위해서는 ActionChains를 사용하면 된다. source 요소에서 target 요소로 Drag & Drop을 수행한다.
from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(source, target).perform()
https://selenium-python.readthedocs.io/index.html
Selenium with Python — Selenium Python Bindings 2 documentation
Note This is not an official documentation. If you would like to contribute to this documentation, you can fork this project in GitHub and send pull requests. You can also send your feedback to my email: baiju.m.mail AT gmail DOT com. So far 50+ community
selenium-python.readthedocs.io
'App Programming > Web Crawler' 카테고리의 다른 글
[Web Crawler] 조회결과를 수집하고 txt 파일로 저장하기 (0) | 2022.02.16 |
---|---|
[Web Crawler] 셀레니움 (Selenium) (4) (0) | 2022.02.15 |
[Web Crawler] 셀레니움 (Selenium) (2) (0) | 2022.02.15 |
[Web Crawler] 셀레니움 (Selenium) (1) (0) | 2022.02.15 |
[Web Crawler] BeautifulSoup으로 다양한 데이터 추출하기 (0) | 2022.02.14 |