이 영역을 누르면 첫 페이지로 이동
나눔코딩 블로그의 첫 페이지로 이동

나눔코딩

페이지 맨 위로 올라가기

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

나눔코딩

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

  • 2020.06.06 07:28
  • 14. Python/Selenium
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('닫기')
Colored by Color Scripter
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)))
 
Colored by Color Scripter
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)
 
Colored by Color Scripter
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()
 
Colored by Color Scripter
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

이 글은 (새창열림) 본 저작자 표시 규칙 하에 배포할 수 있습니다. 자세한 내용은 Creative Commons 라이선스를 확인하세요.
Creative Commons
본 저작자 표시

'14. Python > Selenium' 카테고리의 다른 글

파이썬을 이용하여 인프런 동영상 다운로드 공부  (9) 2021.06.28

댓글

댓글을 사용할 수 없습니다.

이 글 공유하기

  • 구독하기

    구독하기

  • 카카오톡

    카카오톡

  • 트위터

    트위터

  • Facebook

    Facebook

  • 카카오스토리

    카카오스토리

  • 밴드

    밴드

  • 네이버 블로그

    네이버 블로그

  • Pocket

    Pocket

  • Evernote

    Evernote

다른 글

  • 파이썬을 이용하여 인프런 동영상 다운로드 공부

    파이썬을 이용하여 인프런 동영상 다운로드 공부

    2021.06.28
다른 글 더 둘러보기

정보

나눔코딩 블로그의 첫 페이지로 이동

나눔코딩

  • 나눔코딩의 첫 페이지로 이동

검색

메뉴

  • 홈
  • 태그
  • 방명록

카테고리

  • 분류 전체보기 (316)
    • ∞. 읽은 거리 (3)
    • ∞. 기술 면접 (61)
      • 1. 자료구조 (0)
      • 2. 네트워크 (9)
      • 3. 운영체제 (11)
      • 4. 데이터베이스 (13)
      • 5. 디자인 패턴 (0)
      • 6. 알고리즘 (0)
      • 7. 자바 (15)
      • 8. 자바스크립트 (7)
      • 9. 스프링 (5)
      • 10. 시큐리티 (1)
      • 11. 기타 (0)
      • 12. Vue (0)
    • ∞. 웹개발 유용한 사이트 (14)
    • ∞. 트러블 슈팅 + TIL (7)
    • 00. 출발 (9)
    • 01. 엑셀 (9)
      • 기초 (4)
      • 컴활 1급 (4)
      • VBA (0)
    • 02. 엑세스 (9)
      • 기초 (5)
      • 컴활 1급 (4)
    • 04. Oracle (1)
      • 기초 (1)
    • 03. JAVA (8)
      • 기초 (7)
      • 객체지향 프로그래밍 (0)
    • 05. HTML (13)
      • 기초 (1)
      • css (10)
      • sass (0)
      • less (0)
    • 06. Javascript (16)
      • 기초 (13)
      • ES6 모듈 (2)
      • Canvas (0)
    • 07. JSP (0)
      • 기초 (0)
    • 08. jQuery (0)
      • 기초 (0)
    • 09. BootStrap (1)
      • 기초 (0)
      • v4 - Layout (1)
    • 10. Spring (30)
      • 기초 (3)
      • 실험 (4)
      • MVC (1)
      • BOOT (6)
      • Security (10)
      • Lib (Library) (2)
      • 벤치마킹 (0)
      • JUnit5 (2)
      • DevTools (0)
      • Socket (1)
      • Batch (0)
      • Mobile (0)
      • WebFlux (0)
      • Cloud (0)
      • Thymleaf (0)
      • Actuator (0)
      • 성능 테스트 (1)
    • 11. JetBrains (34)
      • 기초 (1)
      • IntelliJ IDEA (33)
      • WebStorm (0)
      • Pycham (0)
    • 12. API (0)
      • 기초 (0)
      • 네이버 API (0)
      • 카카오 API (0)
      • 구글 API (0)
      • 인스타그램 API (0)
    • 13. AutoHotkey (1)
    • 14. Python (8)
      • 기초 (3)
      • Selenium (2)
      • Beautiful Soup (0)
      • openpyxl (1)
      • Pyqt5 (0)
      • Deep learning (open CV) (0)
      • Geocoder (0)
      • Anaconda (0)
      • DeepLearning (0)
      • Jupyter Nootbook (0)
    • 14.5. R (0)
    • 15. JMeter (0)
      • 다운로드 (0)
    • 16. Vue JS (23)
      • 기초 (3)
      • Vue 2 (15)
      • Vue 3 (5)
      • Vuetify 2.5.8 (0)
    • 17. Git (12)
      • 기초 (8)
      • ItelliJ IDEA (4)
      • SourceTree (0)
    • 18. AWS (5)
      • 기초 (2)
      • Jira (3)
    • 19. Naver Cloud Platform (0)
    • 20. Google Cloud Platform (0)
      • 기초 (0)
      • stt & tts (0)
    • 21. Kotlin (0)
    • 22. Android (0)
      • 기초 (0)
      • Java (0)
      • Kotlin (0)
      • Flutter FrameWork (0)
    • 23. Clean Code [JAVA] (1)
    • 24. BuildTool (1)
      • Maven (1)
      • Gradle (0)
    • 25. 자료 구조와 알고리즘 (18)
      • JAVA (1)
      • Java Script (1)
      • 프로그래머스 (0)
      • 백준 알고리즘 (0)
      • 나의 알고리즘 (14)
      • Brilliant 공부 (0)
    • 26. React (1)
      • 기초 (0)
      • 강의 정리 (1)
    • 27. PostMan (0)
      • 기초 (0)
    • 28. 프로그래머스 (9)
    • 29. Leet Code (0)
    • 30. MySQL (3)
      • 기초 (2)
      • 문제 (1)
    • 73. GraphQL (0)
    • 74. Nuxt JS (0)
    • 75. Electron (0)
    • 76. UX &amp; UI Design Tool (0)
      • 기초 (0)
      • Axure (0)
      • Sketch (0)
      • Figma (0)
    • 77. MarkDown (1)
      • 기초 (1)
    • 78. Tomcat (1)
      • 메모 (1)
    • 79. Element JS (0)
    • 80. Parallax JS (0)
      • 기초 (0)
    • 81. Player JS (0)
      • 기초 (0)
    • 82. Smart Maker (0)
    • 83. Vim (0)
      • 기초 (0)
    • 84. Linux (0)
      • 기초 (0)
      • Centos 7 (0)
      • Ubuntu (0)
    • 85. Node JS (2)
      • 기초 (1)
      • WebRTC (0)
      • NVM (1)
    • 86. Propeller JS (0)
    • 87. FullPage JS (0)
      • 기초 (0)
    • 88. 아두이노 (0)
    • 89. Tensorflow (0)
    • 90. 웹 패킷 분석 (0)
    • 91. 크롬 개발자도구 (0)
    • 92. 디자인 패턴 (7)
      • 생성(Creational) (3)
      • 구조(Structral) (1)
      • 행위(Behavioral) (2)
      • SOLID 패턴 (0)
    • 95. Linux Shell Script (0)
    • 96. 구글 애널리스틱 (0)
    • 97. ffmpeg (0)
    • 98. ShareX (1)
    • 자료실 (0)
    • 기타 (2)

인기 글

공지사항

태그

  • 졵
  • 엑셀 가운데맞춤
  • 엑셀 분석작업
  • 엑셀 기타작업
  • 엑셀 글씨
  • 엑셀 기본작업
  • 엑셀 표시형식
  • 깁

나의 외부 링크

  • 비전공자 개발자
  • 자바 디자인 패턴
  • 자바 디자인 패턴
  • 스프링 블로그
  • 해킹보안 & 웹 관련
  • ERD 생성
  • 전문 기술 블로그
  • Servlet에 대한 개념없이 스프링을 했네요?
  • 스프링 FitlerChainList
  • 알고리즘 파워 블로그

정보

THE HEYDAZE의 나눔코딩

나눔코딩

THE HEYDAZE

블로그 구독하기

  • 구독하기
  • RSS 피드

방문자

  • 전체 방문자
  • 오늘
  • 어제

티스토리

  • 티스토리 홈
  • 이 블로그 관리하기
  • 글쓰기
Powered by Tistory / Kakao. © THE HEYDAZE. Designed by Fraccino.

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.