파이썬 크롤링 (beautifulsoup, selenium 활용)

|

패스트캠퍼스 컴퓨터공학 입문 수업을 듣고 중요한 내용을 정리했습니다.
개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.

Scraping vs Crawling vs Parsing

  • 추천도서
  • 스크랩핑(scraping) : 데이터를 수집하는 행위
  • 크롤링(Crawling) : 조직적 자동화된 방법으로 월드와이드웹을 탐색 하는 것
  • 파싱(parsing) : 문장 혹은 문서를 구성 성분으로 분해하고 위계관계를 분석하여 문장의 구조를 결정하는 것

beautifulsoup을 사용한 스크랩핑 1

beautifulsoup

  • 공식문서
  • BeautifulSoup 모듈은 HTML과 XML을 파싱하는 데에 사용되는 파이썬 라이브러리
  • 설치
$ pip install beautifulsoup4 $ pip list 
  • 목표 :https://www.rottentomatoes.com 사이트 메인화면의 Top Box Office에 해당하는 영화 제목과 링크 리스트를 가져온다.
from urllib.request import urlopen from bs4 import BeautifulSoup url = "https://www.rottentomatoes.com/" html = urlopen(url) source = html.read() # 바이트코드 type으로 소스를 읽는다. html.close() # urlopen을 진행한 후에는 close를 한다. soup = BeautifulSoup(source, "html5lib") # 파싱할 문서를 BeautifulSoup 클래스의 생성자에 넘겨주어 문서 개체를 생성, 관습적으로 soup 이라 부름 table = soup.find(id="Top-Box-Office") movies = table.find_all(class_="middle_col") for movie in movies: title = movie.get_text() print(title, end=' ') link = movie.a.get('href') url = 'https://www.rottentomatoes.com' + link print(url) 
  • 결과화면
The Fate of the Furious https://www.rottentomatoes.com/m/the_fate_of_the_furious The Boss Baby https://www.rottentomatoes.com/m/the_boss_baby Beauty and the Beast https://www.rottentomatoes.com/m/beauty_and_the_beast_2017 .... .... 

beautifulsoup을 사용한 스크랩핑 2

  • 목표 : stack overflow 에서 python 검색 결과 질문 리스트와 링크를 가져온다.
from urllib.request import urlopen from bs4 import BeautifulSoup page = urlopen("http://stackoverflow.com/questions/tagged/python") document = page.read() page.close() soup = BeautifulSoup(document, 'html5lib') questions = soup.find(id="questions") questions_list = questions.find_all("a", class_="question-hyperlink") for question in questions_list: print(question.get_text()) print('http://stackoverflow.com' + question.get('href')) 
  • 결과화면
Mutually exclusive many-to-many relationship in Django models http://stackoverflow.com/questions/43657599/mutually-exclusive-many-to-many-relationship-in-django-models How can I get the index of selected item in a treeview? http://stackoverflow.com/questions/43657591/how-can-i-get-the-index-of-selected-item-in-a-treeview How to install Tkinter module with python 2.7.5 in Redhat linux 7? http://stackoverflow.com/questions/43657590/how-to-install-tkinter-module-with-python-2-7-5-in-redhat-linux-7 Grouping columns in python tabulate alphabetically http://stackoverflow.com/questions/43657584/grouping-columns-in-python-tabulate-alphabetically ... ... 

selenium을 사용한 크롤링(Crawling)

  • beautifulsoup은 사용자 행동을 특정해서 데이터를 가져올 수 없다.
  • 사용자의 행동을 동적으로 추가하려면 selenium이 필요하다.

selenium 및 웹 드라이버 설치

  • selenium 설치
  • Selenium은 테스트 코드 실행으로 브라우저에서의 액션을 테스트 할 수 있게 해주는 테스팅 도구
$ pip install selenium 
  • geckodriver 설치
  • geckodriver 다운로드 후 압축을 풀고, usr/local/bin 경로에 옮긴다.
  • 드라이버는 브라우저를 띄우고 통제 드라이빙하는 역할을 한다. (WebDriver는 웹 브라우저와 selenium API 사이의 교량 역할을 한다. 테스트될 웹 페이지에 jQuery가 로드되어 있으면 selenium API를 통해서도 그와 관련된 이벤트를 전송할 수 있다. 테스트될 웹 페이지에 특정 css가 로드되어 있으면 이 또한 참조할 수 있다. URL 변경, input 테그의 내용 조작, css 변경 등 해당 웹 페이지의 모든 것을 제어할 수 있다.)
$ sudo mv geckodriver /usr/local/bin 

selenium을 사용한 google 크롤링

  • 목표 : 구글에 접속하여 ‘macbook pro’를 검색하고, 검색 결과 제목을 가져온다.
  • 코드
import os from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By ff_driver = webdriver.Firefox() ff_driver.get("https://www.google.co.kr") query = ff_driver.find_element_by_id("lst-ib").send_keys("macbook pro") ff_driver.find_element_by_name("btnK").click() WebDriverWait(ff_driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "h3.r"))) page_results = ff_driver.find_elements(By.CSS_SELECTOR, "h3.r") for item in page_results: print(item.text) 
  • 결과화면
MacBook Pro - Apple (KR) MacBook Pro 구입하기 - Apple (KR) MacBook Pro 식별 방법 - Apple 지원 Apple MacBook Pro - Best Buy MacBook Pro - Wikipedia MacBook Pro: Thinner Design With New OLED Touch Bar, Order Now Vertical MacBook Pro 2016 – Henge Docks New MacBook Pro - iStore Apple MacBooks: Pro, Air, Original Macbook | B&H Amazon.com: Apple MacBook Pro MF839LL/A 13.3-Inch Laptop with ... 

Reference