Data Engineering/Crawling

[Crawling] Selenium

YSY^ 2020. 8. 5. 15:53

Selenium

  • 웹 브라우저 제어 도구

    • 원래는 웹 어플리케이션 자동 테스트를 위한 목적으로 만들어진 프레임워크.
    • 웹브라우저를 프로그램을 이용해 제어할 수 있다.
  • Request 모듈의 문제점

    • Javascript를 이용한 AJAX 기법의 비동기적 요청 처리 페이지 크롤링이 힘들다.
    • 로그인 후 요청이 가능한 페이지들에 대한 크롤링이 번거롭다.
    • Selenium을 활용하면 이 두가지 모두 쉽게 처리할 수 있다.
  • Selenium 단점

    • 속도가 느림
  • 설치

    • 파이썬 패키지 설치
    • conda install selenium
    • pip install selenium
  • 튜토리얼

!pip install selenium

드라이버

  • 드라이버 : 웹브라우저를 제어하는 프로그램
    • 웹 브라우저별로 제공된다.
    • 위에서 설치한 selenium 패키지의 드라이버객체를 이용해 이 드라이버를 제어하게 된다.

설치

  1. https://www.selenium.dev/downloads/ 이동후 하단의 Browsers 클릭
  2. Chrome Browser 항목의 documentation 링크 클릭
  3. All versions available in Downloads 에서 설치된 크롬브라우져 버전에 맞는 드라이버 선택
  4. 본인 os에 맞는 드라이버 다운로드
  5. 드라이버파일을 현재 주피터 노트북 파일(소스코드) 있는 폴더로 옮겨 놓는다.
    또는 적당한 폴더에 저장후 환경변수 Path에 추가한다.

    드라이버를 OS 환경에 등록

    • windows
      • 환경변수 추가
      • 내컴퓨터 - 속성 - 고급시스템설정 - 환경변수
      • chromedriver의 path를 추가
    • mac
      • chromedriver 파일을 /usr/local/bin 디렉토리로 복사
      • sudo cp ~/Downloads/chromedriver /usr/local/bin

  • 파이썬 경로와 같은 경로에 위치
  • web driver 객체 생성시마다 크롬 드라이버의 경로 설정

주요 메소드

Driver 속성

  • page_source : 현재 페이지의 html 소스를 반환
  • page_source로 html을 받아서 BeautifulSoup으로 크롤링할 원소를 찾을 수 있다.

Driver의 Element 조회 메소드

  • BeautifulSoup을 이용하지 않고 셀레늄 자체 parser를 이용할 수 있다.
  • 조회결과 : WebElement
  • find_element_xxxx : 조건을 만족하는 요소 하나를 찾는다.
    • find_element_by_id()
      • 태그의 id속성으로 element 조회
    • find_element_by_class_name()
      • 태그의 class속성으로 element 조회
    • find_element_by_css_selector()
      • css selector로 element 조회
    • find_element_by_name()
      • 입력 태그의 name 속성으로 element 조회
  • find_elements_xxx : 조건을 만족하는 모든 요소를 찾는다.
    • find_elements_by_id()
    • find_elements_by_class_name()
    • find_elements_by_css_selector()
    • find_elements_by_name()

WebElement (조회결과) 메소드 / 속성

  • 메소드
    • get_attribute('속성명') : 태그의 속성값 조회
    • send_keys("문자열") : 입력폼에 문자열 값을 입력.
    • click() : element를 클릭
    • submit() : element가 Form인 경우 폼 전송
    • clear() : element가 입력폼인 경우 텍스트를 지운다.
    • 위 조회 메소드들 : 하위의 elements들 조회
  • 속성
    • text : 태그내의 텍스트
    • tag_name : 태그이름
from selenium.webdriver import Chrome
driver = Chrome()
driver.get('https://www.naver.com')

#현재페이지의 html source

driver.page_source

#화면크기변경

driver.set_window_size(400,200)

#화면크기조회

driver.get_window.size()

#화면크기최대화

driver.maximize_window()

#화면캡쳐

driver.get_screenshot_as_file('naver_window.png')

#javascript 호출

driver.execute_script('alert(1000)')
alert = driver.switch_to.alert #alert 창 삭제
alert.accept()

#스크롤 위치 조정

driver.execute_script('window.scrollTo(300,400)')
#300 : 가로스크롤위치, 400: 세로스크롤위치

#글입력

#send_keys() keys-키보드
query_input.clear()
query_input.send_keys('python')

셀레늄으로 구글 검색

from selenium.webdriver import Chrome
driver = Chrome()
driver.get('https://www.google.com/')
input_tag = driver.find_element_by_name('q') #<input name='q'>
input_tag.send_keys('python')
btn = driver.find_element_by_name('btnK')
btn.click()

#검색내용

  • link - dic.r>a:href
  • 제목-div.r >a>h3
links = driver.find_elements_by_css_selector('div.r>a')
titles = driver.find_elements_by_css_selector('div.r>a>h3')
print(len(links), len(titles))
for link, title in zip(links, titles):

    print(link.get_attribute('href'), title.text, sep=" - ")

#결과
https://www.python.org/ - Welcome to Python.org
https://wikidocs.net/43 - 1 파이썬 시작하기 - 왕초보를 위한 Python - WikiDocs
https://namu.wiki/w/Python - Python - 나무위키
https://ko.wikipedia.org/wiki/%ED%8C%8C%EC%9D%B4%EC%8D%AC - 파이썬 - 위키백과, 우리 모두의 백과사전
https://en.wikipedia.org/wiki/Python_(programming_language) - Python (programming language) - Wikipedia
https://www.w3schools.com/python/ - Python Tutorial - W3Schools
https://www.codecademy.com/learn/learn-python - Learn Python 2 | Codecademy

페이지/element 로딩 대기

  • time.sleep(초)

    • 강제적으로 지정한 초만큼 대기시킨다.
  • driver.implicitly_wait(초)

    • 페이지 로딩을 대기한다.
    • 지정한 초는 최대 대기 시간으로 그전에 페이지가 로딩되면 다음으로 넘어간다.
  • WebDriverWait 사용

    • 특정 element가 loading 되기를 기다린다.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# By.조회방식, 
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "selector")))
#             driver  기다릴시간   특정 요소(element)가 나타날때까지  (튜플: 요소조회방식, 대상)
728x90
반응형