SlideShare a Scribd company logo
The beginner’s guide to
웹 크롤링
Web crawling
2015-10-23
Lucy Park
me@lucypark.kr
스크래핑
(Scraping)
어젯밤
자료를 열심히 만들다가 생긴 일
제 소개
• 박사과정 n년차
• 데이터마이닝 전공
• “Yak shaver”
– 대한민국 정치의 모든 것(http://pokr.kr),
KoNLPy(http://konlpy.org) 등을 만드는데 참여
• 현재는 졸업을 위해 칩거 중
3
목차
1. 초간단 손 스크래핑
2. 용어 정리: 크롤링? 스크래핑?
3. 파이썬 3분만에 시작하기 (초간단 문법)
4. 국회 회의록 스크래퍼 갖다 쓰기
5. 국회 회의록 스크래퍼 직접 만들어보기
참고자료
4
초간단 손 스크래핑! 3단계
1. Scrape하려는 웹페이지 목록 만들기
2. 웹페이지 전체 다운로드 받기
3. 웹페이지 parsing
5
초간단 손 스크래핑! 3단계
1. Scrape하려는 웹페이지 목록 만들기
(일단 네 개만)
http://movie.naver.com/movie/bi/mi/basic.nhn?code=121048
http://movie.naver.com/movie/bi/mi/basic.nhn?code=129049
http://movie.naver.com/movie/bi/mi/basic.nhn?code=118917
http://movie.naver.com/movie/bi/mi/basic.nhn?code=114278
6
초간단 손 스크래핑! 3단계
1. Scrape하려는 웹페이지 목록 만들기
2. 웹페이지 목록 전체 다운로드 받기
7
초간단 손 스크래핑! 3단계
1. Scrape하려는 웹페이지 목록 만들기
2. 웹페이지 전체 다운로드 받기
3. 웹페이지 parsing
찾음! 8
그런데 긁고 싶은 페이지가 1000개라면?
9
옵션 1:
대학원생을 시킨다*
* 이건 제가 대학원생이 아니었으면 못할 농담 10
옵션 2:
컴퓨터를 시킨다 낙찰!
11
목차
1. 초간단 손 스크래핑
2. 용어 정리: 크롤링? 스크래핑?
3. 파이썬 3분만에 시작하기 (초간단 문법)
4. 국회 회의록 스크래퍼 갖다 쓰기
5. 국회 회의록 스크래퍼 직접 만들어보기
참고자료
12
용어 정리
이미지 출처:
https://en.wikipedia.org/wiki/Internet#/media/File:Internet_map_102
4_-_transparent,_inverted.png
• 인터넷 (the Internet)
– 네트워크의 네트워크
– 여러 기기 간 연결된 물리적 구조 (IoT!)
13
용어 정리
• 웹 (the Web, www, World Wide Web)
– 인터넷 상에 존재하는 거대한 정보 공간
– 47.7억 개의 웹페이지낄 연결되어 있음
* http://www.worldwidewebsize.com/
14
용어 정리
• 웹페이지
– 웹 상의 문서
15
용어 정리
• URL
– Unique resource locator
– 특정 웹페이지로 연결해주는 주소
– 일명 “링크”
http://likms.assembly.go.kr/bill/jsp/BillDetail.jsp?bill_id=PRC_H1W5H1K0Z1M2G1Q0Q5I5T0O5H4O2H8
scheme host path query
* 더 자세한 내용은 위키피디아에
https://en.wikipedia.org/wiki/Uniform_Resource_Locator 16
용어 정리
• 웹브라우저
– 주소창에 URL을 입력하면 웹페이지를 서버에
요청하고 서버로부터 받은 HTML을 해석해서
화면에 띄워주는 프로그램
17
용어 정리
• HTML (1/3)
– Hypertext markup language
– 웹페이지를 작성하는데 사용되는 마크업 언어
– 태그로 HTML 요소(element)를 만든다
– 일반적인 태그 구조:
<태그명 속성명=“속성값” 다른속성명=“다른속성값”>텍스트</태그명>
18
용어 정리
• HTML (2/3)
– 예시 파일: example.html
<h1>제목</h1>
<p>문단 하나</p>
<p class=“special”>문단 둘</p>
<p class=“special”>문단 셋</p>
<a href=http://some.url.com/>링크</a>
<br>
<table id=“my-table” class=“table-condensed table-striped”>
<tr><td>표</td><td>하나</td></tr>
<tr><td>줄</td><td>둘</td></tr>
</table>
p 태그에 “special”이라는 값을 가진 class 속성이 추가된
HTML 요소 두 개
줄바꿈 태그
table 태그에 “my-table”이라는 값을 가진 id 속성과
table-condensed, table-striped의 두 가지 값을 가진
class 속성이 있는 HTML 요소
a 태그에 URL을 href 속성에 담고 있는 HTML 요소
19
용어 정리
• HTML (3/3)
• 예시 파일: example.html
텍스트 에디터*로 열어서 본
example.html
웹 브라우저로 열어서 본
example.html
* 메모장, Notepad++, Vim 등 텍스트 파일을 수정할 수 있는 프로그램.
화면 캡쳐에 있는 에디터는 Sublime Text 2 20
용어 정리
• HTTP
– Hypertext transfer protocol
– Hypertext로 작성된 웹문서를 주고 받는 통신
규약
응답
response
요청
request
내 컴퓨터
서버
21
(좀 더 엄밀한) 용어 정리
• 크롤링
거미가 (spider)
거미줄을 (hyperlink)
기어다니듯(crawling)
World Wide Web
webpage
hyperlink 22
(좀 더 엄밀한) 용어 정리
• 스크래핑
– 정해진 형태의 웹페이지에서 원하는 데이터를
추출하는 작업 (속어: “긁기”)
– 지금 우리가 하려는 것
암살,9.11,8.97 마션,8.73,8.41 인턴,9.04,8.98 리그레션,6.75,7.08
23
목차
1. 초간단 손 스크래핑
2. 용어 정리: 크롤링? 스크래핑?
3. 파이썬 3분만에 시작하기 (초간단 문법)
4. 국회 회의록 스크래퍼 갖다 쓰기
5. 국회 회의록 스크래퍼 직접 만들어보기
참고자료
24
패키지 설치
• R
• Python*
25
install.packages(‘package_name’)
pip install package_name
* 단, 파이썬 쉘 밖에서 실행
패키지 사용
• R
• Python
26
library(‘package_name’)
import package_name
열
• R*
• Python**
27
abc <- c(‘a’, ‘b’, ‘c’)
abc <- append(abc, ‘d’)
abc = [‘a’, ‘b’, ‘c’]
abc.append(‘d’)
* “vector”라 부름
** “list”라 부름
String concatenation
28
• R
• Python
paste(abc, collapse=‘ ‘)
‘ ‘.join(abc)
String substitution
• R
• Python
29
sub(‘b’, ‘n’, ‘beat’)
‘beat’.replace(‘b’, ‘n’)
루프 (1/2)
30
• R
• Python
for (i in 1:4) {
print(i)
}
for i in range(1,5):
print(i)
루프 (2/2)*
31
• R
• Python
a <- 1:3
s <- sapply(a, function(x) x^2)
print(sum(s))
a = range(1,4)
s = [i**2 for i in a]
print(sum(s))
* These two are not directly comparable. In R, apply is a very powerful function for looping. (Much frequently used than for loops.)
On the other hand, in Python, list comprehensions are frequently used.
함수
32
• R
• Python
jiggle <- function(x) {
return(x + 1)
}
def jiggle(x):
return x + 1
파일 출력
33
• R
• Python
write(‘text’, file=‘textfile.txt’)
f = open(‘textfile.txt’, ‘w’)
f.write(‘text’)
f.close()
목차
1. 초간단 손 스크래핑
2. 용어 정리: 크롤링? 스크래핑?
3. 파이썬 3분만에 시작하기 (초간단 문법)
4. 국회 회의록 스크래퍼 갖다 쓰기
5. 국회 회의록 스크래퍼 직접 만들어보기
참고자료
34
팀포퐁의 국회 회의록 스크래퍼
35
https://github.com/teampopong/crawlers/blob/master/meetings/crawl.py
3단계 간단 사용법
1. crawl.py 파일 다운로드 (또는 복사/붙이기)
2. 명령프롬프트에서 python crawl.py 로
스크립트 실행
36
3단계 간단 사용법
1. crawl.py 파일 다운로드 (또는 복사/붙이기)
2. 명령프롬프트에서 python crawl.py 로
스크립트 실행
3. 다운로드 받은 파일 확인
37
PDF 문서에서 텍스트 추출
• pdf2htmlEX
– PDF를 텍스트로 변환
– 다운로드 (윈도우)
38
PDF 문서에서 텍스트 추출
39
파싱은 이하 생략…
목차
1. 초간단 손 스크래핑
2. 용어 정리: 크롤링? 스크래핑?
3. 파이썬 3분만에 시작하기 (초간단 문법)
4. 국회 회의록 스크래퍼 갖다 쓰기
5. 국회 회의록 스크래퍼 직접 만들어보기
참고자료
41
좀 더 똑똑하고(?) 편한(?) 방법
42
http://pokr.kr/meeting/?date=2012-12-31
구조화가 잘 되어 있는 pokr.kr
데이터 스크래핑
43
http://pokr.kr/meeting/19309244267/dialog
페이지 요소 검사
44
좋은 도구.
이 포인터를 이용해서
웹페이지를 클릭하면
해당 HTML 요소를 찾아준다.
우리가 크롤링하고 싶은 곳
페이지 요소 검사
45
우리가 크롤링하고 싶은 곳
class 속성값이 “dialogue”인 div 안에
class 속성값이
“statement”, “issue”, “time” 등인 div가
여러 개 들어 있다!
(그 div 안의 div가 각각 발언, 안건, 시간 cell 하나)
페이지 요소 검사
46
발언
하나
부분
확대
발언자
발언내용
class 속성값이 “statement”인 div 안에
class 속성값이
“speaker”, “content” 등인 div가 여러 개 들어 있다!
파싱 (parsing)
• HTML 문서는 기본적으로 tree 형태이다.
• 방금 전에도:
47
1. class 속성값이 “dialogue”인 div 안에 class 속성값이 “statement”,
“issue”, “time” 등인 div가 여러 개 들어 있다
2. class 속성값이 “statement”인 div 안에 class 속성값이 “speaker”,
“content” 등인 div가 여러 개 들어 있다!
파싱 (parsing)
• HTML 문서는 기본적으로 tree 형태이다.
• 방금 전에도:
48
<div>
class:dialogue
<div>
class:statement
<div>
class:issue
<div>
class:time
<div>
class:statement
<div>
class:speaker
<div>
class:content
…
…
root
XPath 소개
• HTML (또는 XML)을 파싱할때 사용하는 문법
49
root.xpath(‘.//div’)
root 밑에서 모든 div를 찾아라
XPath 소개
• HTML (또는 XML)을 파싱할때 사용하는 문법
50
root.xpath(‘.//div[@class=“dialogue”]’)
root 밑에서 class 속성값이 “dialogue”인 모든 div를 찾아라
XPath 소개
• HTML (또는 XML)을 파싱할때 사용하는 문법
51
root.xpath(‘.//div[@class=“dialogue”]/div’)
root 밑에서 class 속성값이 “dialogue”인 모든 div를 찾고
그 바로 하위에 있는 모든 div를 찾아라
참고:
• 슬래시 한 번 (/): 바로 하위의
• 슬래시 두 번 (//): 모든 하위의
XPath 소개
• HTML (또는 XML)을 파싱할때 사용하는 문법
52
root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’)
root 밑에서 class 속성값이 “dialogue”인 모든 div를 찾고
그 바로 하위에서 class 속성값이 “statement”인 모든 div를 찾아라
참고:
• 슬래시 한 번 (/): 바로 하위의
• 슬래시 두 번 (//): 모든 하위의
XPath + Python
53
# statements라는 변수에 xpath 넣기
statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’)
XPath + Python
54
# statements라는 변수에 xpath 넣기
statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’)
# 각각의 statement에서 speaker, content 정보 추출하기
for statement in statements:
speaker = statement.xpath(‘./div[@class=“speaker”]/div[@class=“person-name”]/text()’)[0]
content = ‘ ‘.join(statement.xpath(‘./div[@class=“content glossary”]/text()’))
XPath + Python
55
# statements라는 변수에 xpath 넣기
statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’)
# 각각의 statement에서 speaker, content 정보 추출하고 newline 제거 후 rows라는 list에 넣기
rows = []
for statement in statements:
speaker = statement.xpath(‘./div[@class=“speaker”]/div[@class=“person-name”]/text()’)[0]
content = ‘ ‘.join(statement.xpath(‘./div[@class=“content glossary”]/text()’))
content = content.replace(‘n’, ‘ ‘).strip()
rows.append([speaker, content])
XPath + Python
56
# statements라는 변수에 xpath 넣기
statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’)
# 각각의 statement에서 speaker, content 정보 추출하고 newline 제거 후 rows라는 list에 넣기
rows = []
for statement in statements:
speaker = statement.xpath(‘./div[@class=“speaker”]/div[@class=“person-name”]/text()’)[0]
content = ‘ ‘.join(statement.xpath(‘./div[@class=“content glossary”]/text()’))
content = content.replace(‘n’, ‘ ‘).strip()
rows.append([speaker, content])
# 파일에 저장
f = open(‘statements.txt’, ‘w’)
f.write(‘n’.join(‘t’.join(row) for row in rows))
f.close()
XPath + Python
57
# statements라는 변수에 xpath 넣기
statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’)
# 각각의 statement에서 speaker, content 정보 추출하고 newline 제거 후 rows라는 list에 넣기
rows = []
for statement in statements:
speaker = statement.xpath(‘./div[@class=“speaker”]/div[@class=“person-name”]/text()’)[0]
content = ‘ ‘.join(statement.xpath(‘./div[@class=“content glossary”]/text()’))
content = content.replace(‘n’, ‘ ‘).strip()
rows.append([speaker, content])
# 파일에 저장
f = open(‘statements.txt’, ‘w’)
f.write(‘n’.join(‘t’.join(row) for row in rows))
f.close()
결과물 확인
58
전체 파싱 코드:
https://gist.github.com/e9t/556fed5ae4d9bda6f1d8#file-parse-py
이제 끝났습니다!
• 어, 근데 한가지가 빠졌네요.
• URL 목록은 어떻게 받을 수 있을까요?
• 숙제입니다…+_+
59
60
참고자료: 스크래퍼
• 박은정, Scraping from the Web
• 강철, 30분만에 따라하는 동시성 스크래퍼,
PyCon Korea, 2014.
61
참고자료: 파이썬
• 박은정, Introduction to Python (on Windows)
• 김태훈, 140분의 파이썬
• 질의 응답: 파이썬 코리아
https://www.facebook.com/groups/pythonkorea/
62

More Related Content

PDF
파이썬을 활용한 웹 크롤링
HWANGTAEYONG
 
PPTX
웹 크롤링 (Web scraping) 의 이해
2minchul
 
PDF
[2018 데이터야놀자] 웹크롤링 좀 더 잘하기
wangwon Lee
 
PPTX
웹수집(Web Crawling)
wang inyoung
 
PPTX
Making Good SEO Reports Portent Webinar
BrightEdge
 
PPTX
Search Query Processing: The Secret Life of Queries, Parsing, Rewriting & SEO
Koray Tugberk GUBUR
 
PPTX
딥 러닝 자연어 처리를 학습을 위한 파워포인트. (Deep Learning for Natural Language Processing)
WON JOON YOO
 
PDF
화성에서 온 개발자, 금성에서 온 기획자
Yongho Ha
 
파이썬을 활용한 웹 크롤링
HWANGTAEYONG
 
웹 크롤링 (Web scraping) 의 이해
2minchul
 
[2018 데이터야놀자] 웹크롤링 좀 더 잘하기
wangwon Lee
 
웹수집(Web Crawling)
wang inyoung
 
Making Good SEO Reports Portent Webinar
BrightEdge
 
Search Query Processing: The Secret Life of Queries, Parsing, Rewriting & SEO
Koray Tugberk GUBUR
 
딥 러닝 자연어 처리를 학습을 위한 파워포인트. (Deep Learning for Natural Language Processing)
WON JOON YOO
 
화성에서 온 개발자, 금성에서 온 기획자
Yongho Ha
 

What's hot (20)

PDF
Crafting Expertise, Authority and Trust with Entity-Based Content Strategy - ...
Jamie Indigo
 
PDF
Web Server SEO: Make your TTFB faster!
Ash New
 
PPTX
Semantic seo and the evolution of queries
Bill Slawski
 
PDF
딥러닝 자연어처리 - RNN에서 BERT까지
deepseaswjh
 
PDF
Aho-Corasick Algorithm(아호 코라식 알고리즘)
Hongjun Jang
 
PDF
[NDC 발표] 모바일 게임데이터분석 및 실전 활용
Tapjoy X 5Rocks
 
PDF
Winning SEO when doing Web Migrations #SMSSYD19
Aleyda Solís
 
PPTX
프로젝트 기획서 발표 - 웹크롤링 (한양대 오픈소스동아리)
Osori Hanyang
 
PDF
Designing Data-Intensive Applications_ The Big Ideas Behind Reliable, Scalabl...
SindhuVasireddy1
 
PPTX
How to Automatically Subcategorise Your Website Automatically With Python
searchsolved
 
PDF
[236] 카카오의데이터파이프라인 윤도영
NAVER D2
 
PPTX
검색엔진이 데이터를 다루는 법 김종민
종민 김
 
PDF
Optimising Your Site Architecture | Andy Chadwick | Brighton SEO
Snippet Digital
 
PPTX
Semantic search
Bill Slawski
 
PPTX
Image Link Building - Turning Your Smartphone Camera Into A Semi-passive Link...
Chris Czermak
 
PDF
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정
Seongyun Byeon
 
PDF
Kathryn Bevan - How To Ace Your Website Migration - Brighton SEO Slides
Kathryn Bevan
 
PDF
Dynamic Rendering - is this really an SEO silver bullet? SMX WEST
Onely
 
PDF
The Ultimate Google Indexing Session
Onely
 
PDF
Passage indexing is likely more important than you think
Dawn Anderson MSc DigM
 
Crafting Expertise, Authority and Trust with Entity-Based Content Strategy - ...
Jamie Indigo
 
Web Server SEO: Make your TTFB faster!
Ash New
 
Semantic seo and the evolution of queries
Bill Slawski
 
딥러닝 자연어처리 - RNN에서 BERT까지
deepseaswjh
 
Aho-Corasick Algorithm(아호 코라식 알고리즘)
Hongjun Jang
 
[NDC 발표] 모바일 게임데이터분석 및 실전 활용
Tapjoy X 5Rocks
 
Winning SEO when doing Web Migrations #SMSSYD19
Aleyda Solís
 
프로젝트 기획서 발표 - 웹크롤링 (한양대 오픈소스동아리)
Osori Hanyang
 
Designing Data-Intensive Applications_ The Big Ideas Behind Reliable, Scalabl...
SindhuVasireddy1
 
How to Automatically Subcategorise Your Website Automatically With Python
searchsolved
 
[236] 카카오의데이터파이프라인 윤도영
NAVER D2
 
검색엔진이 데이터를 다루는 법 김종민
종민 김
 
Optimising Your Site Architecture | Andy Chadwick | Brighton SEO
Snippet Digital
 
Semantic search
Bill Slawski
 
Image Link Building - Turning Your Smartphone Camera Into A Semi-passive Link...
Chris Czermak
 
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정
Seongyun Byeon
 
Kathryn Bevan - How To Ace Your Website Migration - Brighton SEO Slides
Kathryn Bevan
 
Dynamic Rendering - is this really an SEO silver bullet? SMX WEST
Onely
 
The Ultimate Google Indexing Session
Onely
 
Passage indexing is likely more important than you think
Dawn Anderson MSc DigM
 
Ad

Viewers also liked (10)

PPTX
Selenium을 이용한 동적 사이트 크롤러 만들기
Gyuhyeon Jeon
 
PPTX
141118 최창원 웹크롤러제작
Changwon Choe
 
PDF
한국어와 NLTK, Gensim의 만남
Eunjeong (Lucy) Park
 
PDF
[Week2] 데이터 스크래핑
neuroassociates
 
KEY
6장 지능형 웹 크롤링
Chanil Kim
 
PDF
웹크롤러 조사
rupert kim
 
PPTX
Web Crawler 고군분투기
richellin
 
PDF
[PyConKR 2014] 30분만에 따라하는 동시성 스크래퍼
Cheol Kang
 
PPTX
Node.js를 활용한 웹 크롤링(Crawling)
Jeong-gyu Kim
 
PPTX
[Ppt발표팁]효과적인 슬라이드 발표를 위한 10가지 팁
에디티지(Editage Korea)
 
Selenium을 이용한 동적 사이트 크롤러 만들기
Gyuhyeon Jeon
 
141118 최창원 웹크롤러제작
Changwon Choe
 
한국어와 NLTK, Gensim의 만남
Eunjeong (Lucy) Park
 
[Week2] 데이터 스크래핑
neuroassociates
 
6장 지능형 웹 크롤링
Chanil Kim
 
웹크롤러 조사
rupert kim
 
Web Crawler 고군분투기
richellin
 
[PyConKR 2014] 30분만에 따라하는 동시성 스크래퍼
Cheol Kang
 
Node.js를 활용한 웹 크롤링(Crawling)
Jeong-gyu Kim
 
[Ppt발표팁]효과적인 슬라이드 발표를 위한 10가지 팁
에디티지(Editage Korea)
 
Ad

Similar to The beginner’s guide to 웹 크롤링 (스크래핑) (20)

PDF
Hyperledger farbric build your first network install and analysis
병준 김
 
PDF
HTTP 완벽가이드- 19장 배포시스템
박 민규
 
PDF
데이터 분석 1 - 소개
Jaewook Byun
 
PDF
JetsonTX2 Python
taeseon ryu
 
PPTX
Hyperledger Explorer.pptx
wonyong hwang
 
PDF
UNIX 시스템 2014-2018년 기말시험 기출문제
Lee Sang-Ho
 
PDF
Let'Swift 2023 Swift Macro, 어디다 쓰죠?
williciousk
 
PPTX
XE3 a부터 z까지(1) xe3 구조와 간단한 페이지 만들기
승훈 오
 
PPTX
Python 생태계의 이해
용 최
 
PDF
리눅스 커널 기초 태스크관리
Seungyong Lee
 
PDF
Endnote를 활용한 학술논문 검색법 기초x8
Hana Kim
 
PDF
XECon2015 :: [1-1] 안정수 - XE3 구조 및 기본기
XpressEngine
 
PDF
200725 AWS 클라우드 컴퓨팅으로 배우는 생물정보학 - 덕성여대 강연
Joohyun Han
 
PDF
리얼리눅스 제 1 회 세미나: "리눅스, 제대로 알고 코딩하자!"
리얼리눅스
 
PDF
Red Hat OpenStack 17 저자직강+스터디그룹_5주차
Nalee Jang
 
PDF
제로부터시작하는 Git 두번째 이야기
Mario Cho
 
PDF
Python Korea 2014년 6월 세미나 - Windows 환경에서 Python 개발환경 세팅하기
Joongi Kim
 
PDF
도커 없이 컨테이너 만들기 2편
Sam Kim
 
PDF
Linux tutorial
Hyun-hwan Jeong
 
PPTX
IoT with Raspberry Pi + Node JS - Chapter 1
Park Jonggun
 
Hyperledger farbric build your first network install and analysis
병준 김
 
HTTP 완벽가이드- 19장 배포시스템
박 민규
 
데이터 분석 1 - 소개
Jaewook Byun
 
JetsonTX2 Python
taeseon ryu
 
Hyperledger Explorer.pptx
wonyong hwang
 
UNIX 시스템 2014-2018년 기말시험 기출문제
Lee Sang-Ho
 
Let'Swift 2023 Swift Macro, 어디다 쓰죠?
williciousk
 
XE3 a부터 z까지(1) xe3 구조와 간단한 페이지 만들기
승훈 오
 
Python 생태계의 이해
용 최
 
리눅스 커널 기초 태스크관리
Seungyong Lee
 
Endnote를 활용한 학술논문 검색법 기초x8
Hana Kim
 
XECon2015 :: [1-1] 안정수 - XE3 구조 및 기본기
XpressEngine
 
200725 AWS 클라우드 컴퓨팅으로 배우는 생물정보학 - 덕성여대 강연
Joohyun Han
 
리얼리눅스 제 1 회 세미나: "리눅스, 제대로 알고 코딩하자!"
리얼리눅스
 
Red Hat OpenStack 17 저자직강+스터디그룹_5주차
Nalee Jang
 
제로부터시작하는 Git 두번째 이야기
Mario Cho
 
Python Korea 2014년 6월 세미나 - Windows 환경에서 Python 개발환경 세팅하기
Joongi Kim
 
도커 없이 컨테이너 만들기 2편
Sam Kim
 
Linux tutorial
Hyun-hwan Jeong
 
IoT with Raspberry Pi + Node JS - Chapter 1
Park Jonggun
 

The beginner’s guide to 웹 크롤링 (스크래핑)

  • 1. The beginner’s guide to 웹 크롤링 Web crawling 2015-10-23 Lucy Park [email protected] 스크래핑 (Scraping)
  • 3. 제 소개 • 박사과정 n년차 • 데이터마이닝 전공 • “Yak shaver” – 대한민국 정치의 모든 것(http://pokr.kr), KoNLPy(http://konlpy.org) 등을 만드는데 참여 • 현재는 졸업을 위해 칩거 중 3
  • 4. 목차 1. 초간단 손 스크래핑 2. 용어 정리: 크롤링? 스크래핑? 3. 파이썬 3분만에 시작하기 (초간단 문법) 4. 국회 회의록 스크래퍼 갖다 쓰기 5. 국회 회의록 스크래퍼 직접 만들어보기 참고자료 4
  • 5. 초간단 손 스크래핑! 3단계 1. Scrape하려는 웹페이지 목록 만들기 2. 웹페이지 전체 다운로드 받기 3. 웹페이지 parsing 5
  • 6. 초간단 손 스크래핑! 3단계 1. Scrape하려는 웹페이지 목록 만들기 (일단 네 개만) http://movie.naver.com/movie/bi/mi/basic.nhn?code=121048 http://movie.naver.com/movie/bi/mi/basic.nhn?code=129049 http://movie.naver.com/movie/bi/mi/basic.nhn?code=118917 http://movie.naver.com/movie/bi/mi/basic.nhn?code=114278 6
  • 7. 초간단 손 스크래핑! 3단계 1. Scrape하려는 웹페이지 목록 만들기 2. 웹페이지 목록 전체 다운로드 받기 7
  • 8. 초간단 손 스크래핑! 3단계 1. Scrape하려는 웹페이지 목록 만들기 2. 웹페이지 전체 다운로드 받기 3. 웹페이지 parsing 찾음! 8
  • 9. 그런데 긁고 싶은 페이지가 1000개라면? 9
  • 10. 옵션 1: 대학원생을 시킨다* * 이건 제가 대학원생이 아니었으면 못할 농담 10
  • 12. 목차 1. 초간단 손 스크래핑 2. 용어 정리: 크롤링? 스크래핑? 3. 파이썬 3분만에 시작하기 (초간단 문법) 4. 국회 회의록 스크래퍼 갖다 쓰기 5. 국회 회의록 스크래퍼 직접 만들어보기 참고자료 12
  • 14. 용어 정리 • 웹 (the Web, www, World Wide Web) – 인터넷 상에 존재하는 거대한 정보 공간 – 47.7억 개의 웹페이지낄 연결되어 있음 * http://www.worldwidewebsize.com/ 14
  • 15. 용어 정리 • 웹페이지 – 웹 상의 문서 15
  • 16. 용어 정리 • URL – Unique resource locator – 특정 웹페이지로 연결해주는 주소 – 일명 “링크” http://likms.assembly.go.kr/bill/jsp/BillDetail.jsp?bill_id=PRC_H1W5H1K0Z1M2G1Q0Q5I5T0O5H4O2H8 scheme host path query * 더 자세한 내용은 위키피디아에 https://en.wikipedia.org/wiki/Uniform_Resource_Locator 16
  • 17. 용어 정리 • 웹브라우저 – 주소창에 URL을 입력하면 웹페이지를 서버에 요청하고 서버로부터 받은 HTML을 해석해서 화면에 띄워주는 프로그램 17
  • 18. 용어 정리 • HTML (1/3) – Hypertext markup language – 웹페이지를 작성하는데 사용되는 마크업 언어 – 태그로 HTML 요소(element)를 만든다 – 일반적인 태그 구조: <태그명 속성명=“속성값” 다른속성명=“다른속성값”>텍스트</태그명> 18
  • 19. 용어 정리 • HTML (2/3) – 예시 파일: example.html <h1>제목</h1> <p>문단 하나</p> <p class=“special”>문단 둘</p> <p class=“special”>문단 셋</p> <a href=http://some.url.com/>링크</a> <br> <table id=“my-table” class=“table-condensed table-striped”> <tr><td>표</td><td>하나</td></tr> <tr><td>줄</td><td>둘</td></tr> </table> p 태그에 “special”이라는 값을 가진 class 속성이 추가된 HTML 요소 두 개 줄바꿈 태그 table 태그에 “my-table”이라는 값을 가진 id 속성과 table-condensed, table-striped의 두 가지 값을 가진 class 속성이 있는 HTML 요소 a 태그에 URL을 href 속성에 담고 있는 HTML 요소 19
  • 20. 용어 정리 • HTML (3/3) • 예시 파일: example.html 텍스트 에디터*로 열어서 본 example.html 웹 브라우저로 열어서 본 example.html * 메모장, Notepad++, Vim 등 텍스트 파일을 수정할 수 있는 프로그램. 화면 캡쳐에 있는 에디터는 Sublime Text 2 20
  • 21. 용어 정리 • HTTP – Hypertext transfer protocol – Hypertext로 작성된 웹문서를 주고 받는 통신 규약 응답 response 요청 request 내 컴퓨터 서버 21
  • 22. (좀 더 엄밀한) 용어 정리 • 크롤링 거미가 (spider) 거미줄을 (hyperlink) 기어다니듯(crawling) World Wide Web webpage hyperlink 22
  • 23. (좀 더 엄밀한) 용어 정리 • 스크래핑 – 정해진 형태의 웹페이지에서 원하는 데이터를 추출하는 작업 (속어: “긁기”) – 지금 우리가 하려는 것 암살,9.11,8.97 마션,8.73,8.41 인턴,9.04,8.98 리그레션,6.75,7.08 23
  • 24. 목차 1. 초간단 손 스크래핑 2. 용어 정리: 크롤링? 스크래핑? 3. 파이썬 3분만에 시작하기 (초간단 문법) 4. 국회 회의록 스크래퍼 갖다 쓰기 5. 국회 회의록 스크래퍼 직접 만들어보기 참고자료 24
  • 25. 패키지 설치 • R • Python* 25 install.packages(‘package_name’) pip install package_name * 단, 파이썬 쉘 밖에서 실행
  • 26. 패키지 사용 • R • Python 26 library(‘package_name’) import package_name
  • 27. 열 • R* • Python** 27 abc <- c(‘a’, ‘b’, ‘c’) abc <- append(abc, ‘d’) abc = [‘a’, ‘b’, ‘c’] abc.append(‘d’) * “vector”라 부름 ** “list”라 부름
  • 28. String concatenation 28 • R • Python paste(abc, collapse=‘ ‘) ‘ ‘.join(abc)
  • 29. String substitution • R • Python 29 sub(‘b’, ‘n’, ‘beat’) ‘beat’.replace(‘b’, ‘n’)
  • 30. 루프 (1/2) 30 • R • Python for (i in 1:4) { print(i) } for i in range(1,5): print(i)
  • 31. 루프 (2/2)* 31 • R • Python a <- 1:3 s <- sapply(a, function(x) x^2) print(sum(s)) a = range(1,4) s = [i**2 for i in a] print(sum(s)) * These two are not directly comparable. In R, apply is a very powerful function for looping. (Much frequently used than for loops.) On the other hand, in Python, list comprehensions are frequently used.
  • 32. 함수 32 • R • Python jiggle <- function(x) { return(x + 1) } def jiggle(x): return x + 1
  • 33. 파일 출력 33 • R • Python write(‘text’, file=‘textfile.txt’) f = open(‘textfile.txt’, ‘w’) f.write(‘text’) f.close()
  • 34. 목차 1. 초간단 손 스크래핑 2. 용어 정리: 크롤링? 스크래핑? 3. 파이썬 3분만에 시작하기 (초간단 문법) 4. 국회 회의록 스크래퍼 갖다 쓰기 5. 국회 회의록 스크래퍼 직접 만들어보기 참고자료 34
  • 35. 팀포퐁의 국회 회의록 스크래퍼 35 https://github.com/teampopong/crawlers/blob/master/meetings/crawl.py
  • 36. 3단계 간단 사용법 1. crawl.py 파일 다운로드 (또는 복사/붙이기) 2. 명령프롬프트에서 python crawl.py 로 스크립트 실행 36
  • 37. 3단계 간단 사용법 1. crawl.py 파일 다운로드 (또는 복사/붙이기) 2. 명령프롬프트에서 python crawl.py 로 스크립트 실행 3. 다운로드 받은 파일 확인 37
  • 38. PDF 문서에서 텍스트 추출 • pdf2htmlEX – PDF를 텍스트로 변환 – 다운로드 (윈도우) 38
  • 41. 목차 1. 초간단 손 스크래핑 2. 용어 정리: 크롤링? 스크래핑? 3. 파이썬 3분만에 시작하기 (초간단 문법) 4. 국회 회의록 스크래퍼 갖다 쓰기 5. 국회 회의록 스크래퍼 직접 만들어보기 참고자료 41
  • 42. 좀 더 똑똑하고(?) 편한(?) 방법 42 http://pokr.kr/meeting/?date=2012-12-31
  • 43. 구조화가 잘 되어 있는 pokr.kr 데이터 스크래핑 43 http://pokr.kr/meeting/19309244267/dialog
  • 44. 페이지 요소 검사 44 좋은 도구. 이 포인터를 이용해서 웹페이지를 클릭하면 해당 HTML 요소를 찾아준다. 우리가 크롤링하고 싶은 곳
  • 45. 페이지 요소 검사 45 우리가 크롤링하고 싶은 곳 class 속성값이 “dialogue”인 div 안에 class 속성값이 “statement”, “issue”, “time” 등인 div가 여러 개 들어 있다! (그 div 안의 div가 각각 발언, 안건, 시간 cell 하나)
  • 46. 페이지 요소 검사 46 발언 하나 부분 확대 발언자 발언내용 class 속성값이 “statement”인 div 안에 class 속성값이 “speaker”, “content” 등인 div가 여러 개 들어 있다!
  • 47. 파싱 (parsing) • HTML 문서는 기본적으로 tree 형태이다. • 방금 전에도: 47 1. class 속성값이 “dialogue”인 div 안에 class 속성값이 “statement”, “issue”, “time” 등인 div가 여러 개 들어 있다 2. class 속성값이 “statement”인 div 안에 class 속성값이 “speaker”, “content” 등인 div가 여러 개 들어 있다!
  • 48. 파싱 (parsing) • HTML 문서는 기본적으로 tree 형태이다. • 방금 전에도: 48 <div> class:dialogue <div> class:statement <div> class:issue <div> class:time <div> class:statement <div> class:speaker <div> class:content … … root
  • 49. XPath 소개 • HTML (또는 XML)을 파싱할때 사용하는 문법 49 root.xpath(‘.//div’) root 밑에서 모든 div를 찾아라
  • 50. XPath 소개 • HTML (또는 XML)을 파싱할때 사용하는 문법 50 root.xpath(‘.//div[@class=“dialogue”]’) root 밑에서 class 속성값이 “dialogue”인 모든 div를 찾아라
  • 51. XPath 소개 • HTML (또는 XML)을 파싱할때 사용하는 문법 51 root.xpath(‘.//div[@class=“dialogue”]/div’) root 밑에서 class 속성값이 “dialogue”인 모든 div를 찾고 그 바로 하위에 있는 모든 div를 찾아라 참고: • 슬래시 한 번 (/): 바로 하위의 • 슬래시 두 번 (//): 모든 하위의
  • 52. XPath 소개 • HTML (또는 XML)을 파싱할때 사용하는 문법 52 root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’) root 밑에서 class 속성값이 “dialogue”인 모든 div를 찾고 그 바로 하위에서 class 속성값이 “statement”인 모든 div를 찾아라 참고: • 슬래시 한 번 (/): 바로 하위의 • 슬래시 두 번 (//): 모든 하위의
  • 53. XPath + Python 53 # statements라는 변수에 xpath 넣기 statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’)
  • 54. XPath + Python 54 # statements라는 변수에 xpath 넣기 statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’) # 각각의 statement에서 speaker, content 정보 추출하기 for statement in statements: speaker = statement.xpath(‘./div[@class=“speaker”]/div[@class=“person-name”]/text()’)[0] content = ‘ ‘.join(statement.xpath(‘./div[@class=“content glossary”]/text()’))
  • 55. XPath + Python 55 # statements라는 변수에 xpath 넣기 statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’) # 각각의 statement에서 speaker, content 정보 추출하고 newline 제거 후 rows라는 list에 넣기 rows = [] for statement in statements: speaker = statement.xpath(‘./div[@class=“speaker”]/div[@class=“person-name”]/text()’)[0] content = ‘ ‘.join(statement.xpath(‘./div[@class=“content glossary”]/text()’)) content = content.replace(‘n’, ‘ ‘).strip() rows.append([speaker, content])
  • 56. XPath + Python 56 # statements라는 변수에 xpath 넣기 statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’) # 각각의 statement에서 speaker, content 정보 추출하고 newline 제거 후 rows라는 list에 넣기 rows = [] for statement in statements: speaker = statement.xpath(‘./div[@class=“speaker”]/div[@class=“person-name”]/text()’)[0] content = ‘ ‘.join(statement.xpath(‘./div[@class=“content glossary”]/text()’)) content = content.replace(‘n’, ‘ ‘).strip() rows.append([speaker, content]) # 파일에 저장 f = open(‘statements.txt’, ‘w’) f.write(‘n’.join(‘t’.join(row) for row in rows)) f.close()
  • 57. XPath + Python 57 # statements라는 변수에 xpath 넣기 statements = root.xpath(‘.//div[@class=“dialogue”]/div[@class=“statement”]’) # 각각의 statement에서 speaker, content 정보 추출하고 newline 제거 후 rows라는 list에 넣기 rows = [] for statement in statements: speaker = statement.xpath(‘./div[@class=“speaker”]/div[@class=“person-name”]/text()’)[0] content = ‘ ‘.join(statement.xpath(‘./div[@class=“content glossary”]/text()’)) content = content.replace(‘n’, ‘ ‘).strip() rows.append([speaker, content]) # 파일에 저장 f = open(‘statements.txt’, ‘w’) f.write(‘n’.join(‘t’.join(row) for row in rows)) f.close()
  • 58. 결과물 확인 58 전체 파싱 코드: https://gist.github.com/e9t/556fed5ae4d9bda6f1d8#file-parse-py
  • 59. 이제 끝났습니다! • 어, 근데 한가지가 빠졌네요. • URL 목록은 어떻게 받을 수 있을까요? • 숙제입니다…+_+ 59
  • 60. 60
  • 61. 참고자료: 스크래퍼 • 박은정, Scraping from the Web • 강철, 30분만에 따라하는 동시성 스크래퍼, PyCon Korea, 2014. 61
  • 62. 참고자료: 파이썬 • 박은정, Introduction to Python (on Windows) • 김태훈, 140분의 파이썬 • 질의 응답: 파이썬 코리아 https://www.facebook.com/groups/pythonkorea/ 62