14. Python/Selenium

06. 파이썬 Selenium & ChromeDriver (셀레니움 & 크롬드라이버)

THE HEYDAZE 2020. 6. 6. 07:28
OS Windows 10 Home 64bit 버전 1903 (OS 빌드 18362.836)
python 3.6.0
Tool pycham 2020.1.1 Community

 

#1. 셀레니움(Selenium) 설치

Terminal(CMD) 에

pip install -U selenium 

입력

또는 아래와 같이 pycham 기능을 이용해 다운

이미지 클릭

 

#2. 크롬드라이버 다운로드
 

Downloads - ChromeDriver - WebDriver for Chrome

WebDriver for Chrome

sites.google.com

크롬 - 설정 - Chrome 정보

크롬 버전에 맞는 Chrome Driver 를 다운로드 한다.

(버전 다르면 실행 오류 발생)

 

#3. 프로젝트 생성

PyCharm Community 무료버전

 

다운로드 PyCharm: JetBrains가 만든 전문 개발자용 Python IDE

최신 버전 다운로드: PyCharm (Windows, macOS, Linux)

www.jetbrains.com

 

프로젝트 생성

 

프로젝트명 입력

 

파이썬 버전 설정

 

py 파일 생성

 

Chrome Driver 파일이동 

아까 전에 다운받았던 ChromeDriver 를 옮겨준다

#4 ChromeDriver 실행

크롬드라이버 실행 (이미지 클릭)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from selenium import webdriver
 
# 크롬 드라이버
driver = webdriver.Chrome('./chromedriver.exe')
 
try:
    # URL
    driver.get('https://www.naver.com')
 
    # 요소
    elem = driver.find_element_by_class_name('link_login')
 
    # 요소 클릭
    elem.click()
 
    driver.switch_to_alert()
except Exception as e:
    print(e)
 
finally:
    # 드라이버 종료
    driver.close()
    print('닫기')
cs

 

Selenium & Chrome Driver
요소 가져오기 elem = driver.find_element_by_class_name('blue') 클래스명이 blue 인 요소
여러 요소 가져오기 (elem[0] = 첫번째) elem = driver.find_elements_by_tag_name('td') td 태그 모두를 list로
n번째 요소 가져오기 (td[1] = 첫번째) elem = driver.find_element_by_tag_name('td[1]') td 첫번째
요소 텍스트 가져오기 elem.text div, span, li, td 텍스트
요소 값 가져오기 elem.get_attribute('value') input, textarea 값
요소 텍스트, 값 지우기 elem.clear() 지우기
클릭 elem.click() 해당요소 클릭
입력 elem.send_keys('입력할 내용') input, textarea 내용 입력
요소 대기 driver.implicitly_wait(10) 해당 요소를 10초동안 찾음
열린 창목록 출력 print(driver.window_handles) 기본창, 팝업창 등
팝업 전환 driver.switch_to_window(driver.window_handles[번호]) 해당 윈도우 번호로 전환
Alert 창 전환 driver.switch_to_alert() 알터창으로 전환

 

#5. xPath
 

XPath Tutorial

XPath Tutorial What is XPath? XPath is a major element in the XSLT standard. XPath can be used to navigate through elements and attributes in an XML document. XPath stands for XML Path Language XPath uses "path like" syntax to identify and navigate nodes i

www.w3schools.com

특정한 요소를 선택하기 위해 xPath 를 이용한다

xPath 기본
일치 <button>완료</button>
<button>완료2</button>
driver.find_element_by_xpath('*//button[text()="완료"]')
포함 <button>완료</button>
<button>완료2</button>
driver.find_element_by_xpath('*//button[contains(text(),"완료")]')
속성 <button type="submit">완료</button>
<button type="reset">리셋</button>
driver.find_element_by_xpath('*//button[@type="submit"]')
AND <button id="btn_1" type="submit">완료</button>
<button type="submit">완료</button>
driver.find_element_by_xpath('*//button[@type="submit" and @id="btn_1"]')
OR <button id="btn_1" type="submit">완료</button>
<button type="submit">완료</button>
driver.find_element_by_xpath('*//button[@type="submit" or @id="btn_1"]')

 

#6 Wait

특정 exception 을 무시하는 wait 처리

1
2
3
4
5
6
7
8
9
10
11
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
 
my_element_id = 'something123'
ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,)
your_element = WebDriverWait(your_driver, some_timeout,ignored_exceptions=ignored_exceptions)\
                        .until(expected_conditions.presence_of_element_located((By.ID, my_element_id)))
 
cs

 

지정한 시간동안 true를 반환 할 때 까지의 wait 처리

1
2
3
4
5
6
7
8
9
10
11
from selenium.webdriver.support.ui import WebDriverWait
...
...
def find(driver):
    element = driver.find_elements_by_id("data")
    if element:
        return element
    else:
        return False
element = WebDriverWait(driver, 10).until(find)
 
cs

 

지정시간 동안 해당 요소가 클릭이 가능해 질 때 까지 wait 합니다

(저는 element click intercepted 에러가 발생할 때 사용합니다)

1
2
3
4
browser.find_element_by_css_selector("""#save-post""").click()
 
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "save-post"))).click()
 
cs

 

#7. 기타 참고 사이트

API

 

1. Installation — Selenium Python Bindings 2 documentation

1.2. Downloading Python bindings for Selenium You can download Python bindings for Selenium from the PyPI page for selenium package. However, a better approach would be to use pip to install the selenium package. Python 3.6 has pip available in the standar

selenium-python.readthedocs.io

 

예제

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net