[Python] 31. [Scraping] Selenium 모듈을 이용한 폼과 로그인 인증 통과 테스트

2017. 8. 16. 11:47·빅데이터 프로그래밍/Python
728x90
반응형

[01] Selenium 모듈을 이용한 폼과 로그인 인증 통과 테스트
- 사람처럼 웹페이지와 상호작용이 가능하도록 기능 지원

1. Selenium 설치

C:\Users\soldesk>pip install selenium
Collecting selenium
  Downloading selenium-3.4.1-py2.py3-none-any.whl (931kB)
    100% ■■■■■■■■■■ 942kB 729kB/s
Installing collected packages: selenium
Successfully installed selenium-3.4.1
 
 
2. chromedriver 설치
- https://sites.google.com/a/chromium.org/chromedriver/home
  --> All versions available in Downloads --> Latest Release: ChromeDriver 2.30
 
  'chromedriver_win32.zip' 압축을 풀어 'chromedriver.exe' 파일을
  'C:/Windows/System32' 폴더에 복사
 
 
3. 태그의 검색
 
[실행 화면]
Found <div> element with that class name!
▷ crawler1.selenium1.py
-------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://www.google.co.kr')

try:
    # <div class="logo-subtext">한국</div>
    elem = browser.find_element_by_class_name('logo-subtext')
    print('발견된 태그: <%s>' %(elem.tag_name))
except:
    print('태그를 찾지 못했습니다.')

 

 

4. 페이지 클릭하기

[실행 화면]
브러우저가 실행되어 Google의 이미지 검색으로 자동 이동함.
▷ crawler1.selenium2.py
-------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://www.google.co.kr')

try:
    # <a class="gb_P" data-pid="2" href="https://www.google.co.kr/imghp?hl=ko&tab=wi&ei=6uABWdvbDcrJ0gSeoa7gCw&ved=0EKouCBUoAQ">이미지</a>
    aElement = browser.find_element_by_link_text('이미지')
    print(type(aElement))
    aElement.click() # 마우스 클릭 이벤트 발생
except:
    print('태그를 찾지 못했습니다.')

 
 

 
 
5. 폼의 데이터 전송하기

[실행 화면]
브러우저가 실행되어 Google의 이미지 검색으로 자동 이동하여 '스위스' 이미지를 검색함.

▷ crawler1.selenium3.py
-------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
 
from selenium import webdriver
 
browser = webdriver.Chrome()
browser.get('https://www.google.co.kr/imghp?hl=ko&tab=wi&ei=8hwCWfjtDYWb8QWZq5eIDg&ved=0EKouCBUoAQ')
 
try:
    # <a class="gb_P" data-pid="2" href="https://www.google.co.kr/imghp?hl=ko&tab=wi&ei=6uABWdvbDcrJ0gSeoa7gCw&ved=0EKouCBUoAQ">이미지</a>
    inputEle = browser.find_element_by_id('lst-ib')
    inputEle.send_keys('스위스') # 문장 입력, 키보드 입력 이벤트 발생
    
    # <button class="sbico-c" value="검색" aria-label="Google 검색" id="_fZl" name="btnG" type="submit"><span class="sbico _wtf _Qtf"><svg focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path></svg></span></button>
    submitEle = browser.find_element_by_id('_fZl')
    submitEle.submit()  # 전송
    
except:
    print('태그를 찾지 못했습니다.')

      
-------------------------------------------------------------------------------------
 
 

[실습] Google에서 이미지를 검색하여 자동으로 50개의 이미지를 저장하는 스크립트를 작상하세요.
 
▷ crawler1.google_image.py
-------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------
 
6. Gmail 로그인하기
- Google 로그인은 보안 인증 강화로 추가 단계를 더 진행해야함.
 
[실행 화면]
브러우저가 실행되어 Google의 이미지 검색으로 자동 이동하여 '스위스' 이미지를 검색함.
▷ crawler1.selenium4.py
-------------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
 
from selenium import webdriver
import time
 
browser = webdriver.Chrome()
browser.get('https://accounts.google.com/signin/v2/identifier?continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin')
 
try:
    # <input type="email" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="username" spellcheck="false" tabindex="0" aria-label="이메일 또는 휴대전화" name="identifier" id="identifierId" dir="ltr" data-initial-dir="ltr" data-initial-value="">
    inputEle = browser.find_element_by_id('identifierId')
    inputEle.send_keys('testcell2010@gmail.com') # 키 입력
    
    time.sleep(2)
    
    # <div role="button" id="identifierNext" class="O0WRkf zZhnYe e3Duub C0oVfc Zp5qWd Hj2jlf" jscontroller="VXdfxd" jsaction="click:cOuCgd; mousedown:UX7yZ; mouseup:lbsD7e; mouseenter:tfO1Yc; mouseleave:JywGue;touchstart:p6p2H; touchmove:FwuNnf; touchend:yfqBxc(preventMouseEvents=true|preventDefault=true); touchcancel:JMtRjd;focus:AHmuwe; blur:O22p3e; contextmenu:mg9Pef;" jsshadow="" jsname="tJiF1e" aria-disabled="false" tabindex="0"><div class="Vwe4Vb MbhUzd" jsname="ksKsZd"></div><div class="ZFr60d CeoRYc"></div><content class="CwaK9"><span class="RveJvd snByac">다음</span></content></div>
    nextEle = browser.find_element_by_id('identifierNext')
    nextEle.click()
 
    time.sleep(2)  # 1초, 페이지 이동 시간을 부여함.
    
    # <input type="password" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-password" spellcheck="false" tabindex="0" aria-label="비밀번호 입력" name="password" autocapitalize="off" autocorrect="off" dir="ltr" data-initial-dir="ltr" data-initial-value="">
    passwordEle = browser.find_element_by_name('password')    
    passwordEle.send_keys("69017000") # 패스워드 입력
    
    time.sleep(2)
    
    submitEle = browser.find_element_by_id('passwordNext')
    submitEle.click() # 로그인 버튼
    
except:
    print('태그를 찾지 못했습니다.')
    
         
     
-------------------------------------------------------------------------------------


7. <IFRME>을 사용하는 경우

 
driver.switch_to.frame("loginframe") 
 
elem = driver.find_element_by_id("id") 
elem.send_keys("user_id") 

elem = driver.find_element_by_id("pw") 
elem.send_keys("user_pw") 

elem.submit()

[실습] Daum, Naver, Twitter등에 로그인해보세요.

728x90
반응형

'빅데이터 프로그래밍 > Python' 카테고리의 다른 글

[Python] 33. [MySQL] 서버 실행, 관리자 root계정 암호화, root 접속 설정, 계정 생성  (0) 2017.08.21
[Python] 32. [MySql] 데이터베이스 개론, MySQL 5.6 Potable(개발자 유형) 설치, 한글 깨짐, 처리, 보관, 수정, 삭제  (0) 2017.08.21
[Python] 30. [Scraping] XKCD.com 이미지 다운받기 -- CHECK CHECK CHECK CHECK CHECK  (0) 2017.08.16
[Python] 29. [Scraping] KoNLPy 자연어 처리 패키지, JPype 설치, 명사 분리 추출 후, 단어 사용 빈도 계산하기  (0) 2017.08.16
[Python] 28. [Scraping] 한겨레 신문 뉴스, Naver 뉴스, 동아 일보 뉴스 검색 drawling  (1) 2017.08.16
'빅데이터 프로그래밍/Python' 카테고리의 다른 글
  • [Python] 33. [MySQL] 서버 실행, 관리자 root계정 암호화, root 접속 설정, 계정 생성
  • [Python] 32. [MySql] 데이터베이스 개론, MySQL 5.6 Potable(개발자 유형) 설치, 한글 깨짐, 처리, 보관, 수정, 삭제
  • [Python] 30. [Scraping] XKCD.com 이미지 다운받기 -- CHECK CHECK CHECK CHECK CHECK
  • [Python] 29. [Scraping] KoNLPy 자연어 처리 패키지, JPype 설치, 명사 분리 추출 후, 단어 사용 빈도 계산하기
밍글링글링
밍글링글링
mingling - 밍글링, 밍글밍글링. 코드와 어우러지다. IT/ 프로그래밍/소스
    반응형
    250x250
  • 밍글링글링
    mingling
    밍글링글링
  • 전체
    오늘
    어제
    • 밍글링글링 (407) N
      • Flutter (2)
      • 일상생활 (8)
        • 리뷰 (1)
        • 생활정보 (4)
        • 맛집 (0)
        • 여행 (0)
        • 모든정보 (3)
      • JAVA (126)
        • 개념 (6)
        • 예제 (115)
        • Exception (2)
      • C (1)
        • C (1)
        • C++ (0)
        • C# (0)
      • JS (29)
        • JavaScript (18)
        • JQuery (5)
        • AJax (0)
        • NODE.JS (6)
        • Angular.JS 2.0 (0)
      • WEB (87)
        • HTML (6)
        • CSS (61)
        • JSP (20)
        • JSTL (0)
      • FrameWork (8)
        • Spring (8)
        • BootStrap (0)
        • MyBATIS (0)
        • JUnit (0)
      • 외부 라이브러리 (5)
      • 공유 소스 관리 (5)
        • Git (5)
        • SVN (0)
      • 빅데이터 프로그래밍 (37)
        • Python (37)
        • R Programming (0)
      • DB (7)
        • ORACLE (0)
        • MySql (6)
      • Development Tools (7)
        • StarUML (0)
        • eXERD (0)
        • Eclipse (4)
      • SKILL (6)
        • Migration (0)
        • Security (6)
      • MicroSoft (0)
        • Excel (0)
        • Word (0)
      • Android (0)
      • Server (21)
        • Ubuntu (5)
        • Linux (15)
      • IOS (0)
      • XML (0)
      • 미디어 (0)
      • 공지사항 (3)
      • NETWORK (1)
      • 게임 (4)
        • 피파 (1)
        • 리니지M (0)
        • 배틀그라운드 (1)
        • 듀랑고 (2)
      • 세상 이슈 (6)
      • 일렉트론 (0)
      • 대회 소식 (4)
      • 업무 (2)
      • Express, Vue (6)
      • docker (11)
      • svelte (3)
      • 블록체인 (1)
      • IT (10) N
      • Rust (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    java casting
    ssl 인증서 발급
    nginx ssl 적용
    클론코딩
    React Compiler
    Java Array
    ubuntu
    Rust lang
    AI 코딩 에이전트
    티스토리 자동화
    docker
    spring java
    vue cli
    servlet class
    css transition
    자바 배열
    프런트엔드
    자바 객체 지향
    rust linux
    css table
    gitlab 설치
    nginx
    리눅스 설치
    css float
    css block
    에디터 팁
    자바 생성자
    css list
    러스트
    css perspective
    Node
    svelte
    proxy pass
    API 설계
    Extension Bisect
    css tb
    nginx ssl 설정
    VS Code 팁
    lang rust
    vscode
    자바 exception
    jsp parameter
    jsp include
    오류
    자바 for문
    SSL 인증서
    브라우저 자동화
    vue 설치
    자바 클래스
    mysql db
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
밍글링글링
[Python] 31. [Scraping] Selenium 모듈을 이용한 폼과 로그인 인증 통과 테스트
상단으로

티스토리툴바