본문 바로가기
Back-end/Python

[크롤링] 무작정 시작하기 (2) - 프로젝트 준비

by 허도치 2019. 11. 19.

2019/11/19 - [Back-end/Python] - [크롤링] 무작정 시작하기 (1) - 패키지 선택

 

  이번에는 이전 포스트에 이어서 이번 포스트에서는 프로젝트 셋팅을 하도록하겠다. 크롤링할 대상은 '네이버 뉴스'로 하였으며, 수집한 데이터는 상업적인 목적으로 이용할 의도가 없음을 알려드립니다.

 

 

1. 가상환경생성

   1-1. python에서 프로젝트를 새로 생성하면 가장 먼저해야하는 일은 바로 가상환경을 생성.

1
2
3
4
5
6
7
8
9
10
$ pip install virtualenv      # virtualenv 패키지 설치
 
$ virtualenv --version         # 설치 확인
16.7.7
 
$ virtualenv .venv             # 가상환경 생성
 
$ source .venv/bin/activate  # 가상환경 실행
 
(.venv)$ deactivate            # 가상환경 종료
cs

 

   1-2. 개발환경이 Windows 일 경우

1
2
3
".venv/Scripts/activate" # 가상환경 실행
 
(.venv)$ deactivate             # 가상환경 종료
cs

 

 

2. 패키지 설치 

    2-1. 개발환경을 맞추기위해 scrapy는 1.8.0버전, selenium은 3.141.0버전을 설치한다.

1
$ pip install scrapy==1.8.0 selenium==3.141.0
cs

 

    2-2. Scrapy 명렁어 확인

          - scrapy는 global로 생성되어 command-line에서 명령어를 입력하여 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ scrapy # 명령어 확인
Usage:
  scrapy <command> [options] [args]
 
Available commands:
  bench         Run quick benchmark test
  fetch         Fetch a URL using the Scrapy downloader
  genspider     Generate new spider using pre-defined templates
  runspider     Run a self-contained spider (without creating a project)
  settings      Get settings values
  shell         Interactive scraping console
  startproject  Create new project
  version       Print Scrapy version
  view          Open URL in browser, as seen by Scrapy
 
  [ more ]      More commands available when run from project directory
 
Use "scrapy <command> -h" to see more info about a command
cs

 

3. Scrapy 프로젝트 생성

   3-1. 현재 디렉토리에 프로젝트명이 crawler인 프로젝트 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ scrapy startproject crawler .
 
│  scrapy.cfg
└─crawler
    │  items.py
    │  middlewares.py
    │  pipelines.py
    │  settings.py
    │  __init__.py
    │
    ├─spiders
    │  │  __init__.py
    │  │
    │  └─__pycache__
    └─__pycache__
cs

 

   3-2. 파일별 한줄 요약

         1. scrapy.cfg - 프로젝트 설정 파일, 프로젝트명, settings파일 경로 등을 설정할 수 있음.

         2. spiders - 데이터를 수집하고 가공하는 일을 하는 Worker를 Spider라고 하며, 여러 Spider들이 모여있는 폴더.

         3. items.py - Spider가 작업을 완료한 후 반환하는 결과값의 Schema를 정의하는 파일.

         4. middlewares.py - Spider가 request를 던질때 Proecces를 controll하는 파일, Selenium을 여기에 적용.

         5. pipelines.py - Spider가 response를 받았을 때 처리하는 Process를 controll하는 파일.

         6. settings.py - Spider 실행에 필요한 전반적인 옵션을 설정하는 파일.

 

 

4. Spider 생성

   4-1. 이름이 navernews인 spider를 spiders 폴더에 생성

1
scrapy genspider navernews news.naver.com
cs

 

   4-2. Spider 생성 확인

1
2
3
4
5
6
7
├─spiders
│  │  navernews.py
│  │  __init__.py
│  │
│  └─__pycache__
└─__pycache__
cs

 

   4-3. Spider 실행 확인

1
$ scrapy crawl navernews
cs

 

 

5. Selenium을 위한 Chroem Webdriver설치

   5-1. 78버전 다운로드 - https://chromedriver.storage.googleapis.com/index.html?path=78.0.3904.105/

 

https://chromedriver.storage.googleapis.com/index.html?path=78.0.3904.105/

 

chromedriver.storage.googleapis.com

   5-2. 다운로드 후 압축해제

         - 개발환경이 Windows인 경우, [ chromedriver.exe ]로 확장자가 다름.

 

   5-3. 사용하기 편한 경로로 이동.

         - ./crawler/drivers/chromedriver

1
2
3
4
5
6
7
8
9
10
├─drivers
│      chromedriver
├─spiders
│  │  navernews.py
│  │  __init__.py
│  │
│  └─__pycache__
└─__pycache__
cs

 

6. Selenium 실행 테스트

   6-1. 테스트 스크립작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# selenium_test.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
 
CHROMEDRIVER_PATH = './crawler/drivers/chromedriver' # Windows는 chromedriver.exe로 변경
WINDOW_SIZE = "1920,1080"
 
chrome_options = Options()
chrome_options.add_argument( "--headless" )     # 크롬창이 열리지 않음
chrome_options.add_argument( "--no-sandbox" )   # GUI를 사용할 수 없는 환경에서 설정, linux, docker 등
chrome_options.add_argument( "--disable-gpu" )  # GUI를 사용할 수 없는 환경에서 설정, linux, docker 등
chrome_options.add_argument(f"--window-size={ WINDOW_SIZE }")
chrome_options.add_argument('Content-Type=application/json; charset=utf-8')
 
driver = webdriver.Chrome( executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options )
driver.get( 'https://news.naver.com' )
 
 
cs

 

   6-2. 실행

1
$ python selenium_test.py
cs

 

   6-3. 실행 확인

         - [ headless, no_sandbox, disable-gpu ] 옵션을 사용하여 Chrome 창이 열리지 않도록 제어.

         - 테스트를 위해 위 3개의 옵션을 제거하고 실행하면, 아래와 같이 'Chrome이 자동화된 테스트 소프트웨어에 의해 제어되고 있습니다.'라는 문구와 함께 Chrome이 실행됨.

 

 

이번 포스트에서는 Scrapy와 Selenium 설정을 진행하였으며 다음 포스트에서는 4단계에서 생성한 Spider를 작성하여 네이버 뉴스의 글 목록을 수집할 계획입니다.

댓글