SlideShare una empresa de Scribd logo
1 de 12
Descargar para leer sin conexión
Web Scraping with Python
Chapter 03. Starting to Crawl
SweetK
Ryan Jeong
BEAUTIFUL SOUP 란?
Like its Wonderland namesake,
BeautifulSoup tries to make sense of
the nonsensical; it helps format and
organize the messy web by fixing
bad HTML and presenting us with
easily-traversible Python objects
representing XML structures.
복잡하고 더러운 웹 HTML 코드
소스코드내에서
쉽게 가져올 수 있는
구조화된 Object로
변환
결과출력!
STARTINGTO CRAWL
with Beautiful Soup
연습 1단계 : 특정 페이지에서 모든 링크들 가져오기
결과출력소스
접속한 URL에서
str_root_url = "http://cafe.naver.com/inmacbook"
모든 a 링크들을 가져오고, for 루프를 돌면서,
for link in bsObj.findAll(tag_to_find):
그 안에 있는 attribute 중에서 href의 값들을
str_tmp = link.attrs[attr_to_get]
출력합니다.
print(str_tmp)
* 테스트 사이트는 ‘네이버카페 - 맥쓰사’
TIP
책에는 없지만, 소스코드 라인을 보면,
html = urlopen(str_root_url).read().decode('cp949', 'ignore')
이 부분에서, 밑줄 친 코드가 추가 되어 있음에 주의하라.
이 부분은 한글처리를 위해 본인이 추가하였다.
만약, 위와같이 처리를 하지 않으면, 한글이 모조리 깨져서 보일 것이다.
연습 2단계 : 특정 패턴의 링크들만 가져오기
결과출력소스
다른 부분들은 다 동일하고,
for link in bsObj.findAll(tag_to_find, href=re.compile("^(/ArticleList.nhn?)")):
이 부분 URL에 특정 패턴을 입력했을 뿐이다.
아래는 이전 소스이다. 비교해 보라.
for link in bsObj.findAll(tag_to_find):
연습 3단계 : 링크에, 링크에, 링크에…링크로 들어가기
결과출력소스
지난 소스와 바뀐 부분에 주목할 점은,
1. 패턴과,
(/ArticleList.nhn?|/ArticleRead.nhn?)
2. 들어갔던 링크에 다시 들어 갔는지 여부체크와,
if link.attrs[attr_to_get] not in pages:
3. 재귀호출(recursive calling) 이다.
if link.attrs[attr_to_get] not in pages:
new_page = link.attrs[attr_to_get]
print(new_page)
pages.add(new_page)
get_links(new_page)
* 주의할 점 : Python에서 재귀호출은 1000번으로 제한되어 있다.
연습 4단계 : 링크 타고 들어가기만 하면 뭐하나?
결과출력소스
뭐하러 링크를 타고 들어갔나요?
거기 있는 글을 가져오려고 들어갔습니다.
content = bsObj.find(id = id_to_find_for_content)
이렇게 하면,
id=“tbody” 인 태그를 찾아서 그 안에 있는 컨텐츠를 가져옵니
다. 가져온 컨텐츠는 용도에 따라 가공해서 저장(DB, file 등)하
시면 됩니다.
* 네이버카페의 몸글은 아래 태그 안에 있습니다.
<div class="tbody m-tcol-c" id=“tbody">
...
</div>
연습 6단계 : Scrapy도 써보자!
각자 한 번 해보세요!
(Scrapy는 python 3.x에서 아직 지원안함)
연습 5단계 : 연결된 다른 도메인까지 넘어가서 수집!
Thank youhttp://www.sweetk.co.kr

Más contenido relacionado

Más de Young Oh Jeong

개혁파교의학 12장 솔하 발표본
개혁파교의학 12장 솔하 발표본개혁파교의학 12장 솔하 발표본
개혁파교의학 12장 솔하 발표본Young Oh Jeong
 
개혁파교의학 12장 동혁 발표본
개혁파교의학 12장 동혁 발표본개혁파교의학 12장 동혁 발표본
개혁파교의학 12장 동혁 발표본Young Oh Jeong
 
개혁파교의학 12장 다은 발표본
개혁파교의학 12장 다은 발표본개혁파교의학 12장 다은 발표본
개혁파교의학 12장 다은 발표본Young Oh Jeong
 
개혁파교의학 12장 예건 발표본
개혁파교의학 12장 예건 발표본개혁파교의학 12장 예건 발표본
개혁파교의학 12장 예건 발표본Young Oh Jeong
 
Python machine learning Chapter 07 - PART1
Python machine learning Chapter 07 - PART1Python machine learning Chapter 07 - PART1
Python machine learning Chapter 07 - PART1Young Oh Jeong
 
Python machine learning Chapter 06 - PART1
Python machine learning Chapter 06 - PART1Python machine learning Chapter 06 - PART1
Python machine learning Chapter 06 - PART1Young Oh Jeong
 
Python machine learning Chapter 04 - PART2
Python machine learning Chapter 04 - PART2Python machine learning Chapter 04 - PART2
Python machine learning Chapter 04 - PART2Young Oh Jeong
 
Python machine learning Chapter 02
Python machine learning Chapter 02Python machine learning Chapter 02
Python machine learning Chapter 02Young Oh Jeong
 
10 Scrapping Javascript
10 Scrapping Javascript10 Scrapping Javascript
10 Scrapping JavascriptYoung Oh Jeong
 
07 Cleaning Your Dirty Data
07 Cleaning Your Dirty Data07 Cleaning Your Dirty Data
07 Cleaning Your Dirty DataYoung Oh Jeong
 
푸른아카데미, PART→PARTPRIME
푸른아카데미, PART→PARTPRIME푸른아카데미, PART→PARTPRIME
푸른아카데미, PART→PARTPRIMEYoung Oh Jeong
 
Day by day iPhone Programming
Day by day iPhone ProgrammingDay by day iPhone Programming
Day by day iPhone ProgrammingYoung Oh Jeong
 
네델란드개혁교회역사도식
네델란드개혁교회역사도식네델란드개혁교회역사도식
네델란드개혁교회역사도식Young Oh Jeong
 
Everybody need programming skill. 프로그래밍, 현대인의 교양입니다
Everybody need programming skill. 프로그래밍, 현대인의 교양입니다Everybody need programming skill. 프로그래밍, 현대인의 교양입니다
Everybody need programming skill. 프로그래밍, 현대인의 교양입니다Young Oh Jeong
 
마이크로소프트웨어 2002년 10월호 內, 모바일 관련 서적 리뷰 및 평점
마이크로소프트웨어 2002년 10월호 內, 모바일 관련 서적 리뷰 및 평점마이크로소프트웨어 2002년 10월호 內, 모바일 관련 서적 리뷰 및 평점
마이크로소프트웨어 2002년 10월호 內, 모바일 관련 서적 리뷰 및 평점Young Oh Jeong
 

Más de Young Oh Jeong (18)

개혁파교의학 12장 솔하 발표본
개혁파교의학 12장 솔하 발표본개혁파교의학 12장 솔하 발표본
개혁파교의학 12장 솔하 발표본
 
개혁파교의학 12장 동혁 발표본
개혁파교의학 12장 동혁 발표본개혁파교의학 12장 동혁 발표본
개혁파교의학 12장 동혁 발표본
 
개혁파교의학 12장 다은 발표본
개혁파교의학 12장 다은 발표본개혁파교의학 12장 다은 발표본
개혁파교의학 12장 다은 발표본
 
개혁파교의학 12장 예건 발표본
개혁파교의학 12장 예건 발표본개혁파교의학 12장 예건 발표본
개혁파교의학 12장 예건 발표본
 
About RNN
About RNNAbout RNN
About RNN
 
About RNN
About RNNAbout RNN
About RNN
 
Python machine learning Chapter 07 - PART1
Python machine learning Chapter 07 - PART1Python machine learning Chapter 07 - PART1
Python machine learning Chapter 07 - PART1
 
What is CNN?
What is CNN?What is CNN?
What is CNN?
 
Python machine learning Chapter 06 - PART1
Python machine learning Chapter 06 - PART1Python machine learning Chapter 06 - PART1
Python machine learning Chapter 06 - PART1
 
Python machine learning Chapter 04 - PART2
Python machine learning Chapter 04 - PART2Python machine learning Chapter 04 - PART2
Python machine learning Chapter 04 - PART2
 
Python machine learning Chapter 02
Python machine learning Chapter 02Python machine learning Chapter 02
Python machine learning Chapter 02
 
10 Scrapping Javascript
10 Scrapping Javascript10 Scrapping Javascript
10 Scrapping Javascript
 
07 Cleaning Your Dirty Data
07 Cleaning Your Dirty Data07 Cleaning Your Dirty Data
07 Cleaning Your Dirty Data
 
푸른아카데미, PART→PARTPRIME
푸른아카데미, PART→PARTPRIME푸른아카데미, PART→PARTPRIME
푸른아카데미, PART→PARTPRIME
 
Day by day iPhone Programming
Day by day iPhone ProgrammingDay by day iPhone Programming
Day by day iPhone Programming
 
네델란드개혁교회역사도식
네델란드개혁교회역사도식네델란드개혁교회역사도식
네델란드개혁교회역사도식
 
Everybody need programming skill. 프로그래밍, 현대인의 교양입니다
Everybody need programming skill. 프로그래밍, 현대인의 교양입니다Everybody need programming skill. 프로그래밍, 현대인의 교양입니다
Everybody need programming skill. 프로그래밍, 현대인의 교양입니다
 
마이크로소프트웨어 2002년 10월호 內, 모바일 관련 서적 리뷰 및 평점
마이크로소프트웨어 2002년 10월호 內, 모바일 관련 서적 리뷰 및 평점마이크로소프트웨어 2002년 10월호 內, 모바일 관련 서적 리뷰 및 평점
마이크로소프트웨어 2002년 10월호 內, 모바일 관련 서적 리뷰 및 평점
 

Último

캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스
 
Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Wonjun Hwang
 
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionMOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionKim Daeun
 
Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Wonjun Hwang
 
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Kim Daeun
 
A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)Tae Young Lee
 

Último (6)

캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차캐드앤그래픽스 2024년 5월호 목차
캐드앤그래픽스 2024년 5월호 목차
 
Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)Console API (Kitworks Team Study 백혜인 발표자료)
Console API (Kitworks Team Study 백혜인 발표자료)
 
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution DetectionMOODv2 : Masked Image Modeling for Out-of-Distribution Detection
MOODv2 : Masked Image Modeling for Out-of-Distribution Detection
 
Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)Merge (Kitworks Team Study 이성수 발표자료 240426)
Merge (Kitworks Team Study 이성수 발표자료 240426)
 
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
Continual Active Learning for Efficient Adaptation of Machine LearningModels ...
 
A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)A future that integrates LLMs and LAMs (Symposium)
A future that integrates LLMs and LAMs (Symposium)
 

03 Crawling with Beautiful Soup (네이버 카페 크롤링 하기)

  • 1. Web Scraping with Python Chapter 03. Starting to Crawl SweetK Ryan Jeong
  • 2. BEAUTIFUL SOUP 란? Like its Wonderland namesake, BeautifulSoup tries to make sense of the nonsensical; it helps format and organize the messy web by fixing bad HTML and presenting us with easily-traversible Python objects representing XML structures.
  • 4. 소스코드내에서 쉽게 가져올 수 있는 구조화된 Object로 변환 결과출력!
  • 6. 연습 1단계 : 특정 페이지에서 모든 링크들 가져오기 결과출력소스 접속한 URL에서 str_root_url = "http://cafe.naver.com/inmacbook" 모든 a 링크들을 가져오고, for 루프를 돌면서, for link in bsObj.findAll(tag_to_find): 그 안에 있는 attribute 중에서 href의 값들을 str_tmp = link.attrs[attr_to_get] 출력합니다. print(str_tmp) * 테스트 사이트는 ‘네이버카페 - 맥쓰사’
  • 7. TIP 책에는 없지만, 소스코드 라인을 보면, html = urlopen(str_root_url).read().decode('cp949', 'ignore') 이 부분에서, 밑줄 친 코드가 추가 되어 있음에 주의하라. 이 부분은 한글처리를 위해 본인이 추가하였다. 만약, 위와같이 처리를 하지 않으면, 한글이 모조리 깨져서 보일 것이다.
  • 8. 연습 2단계 : 특정 패턴의 링크들만 가져오기 결과출력소스 다른 부분들은 다 동일하고, for link in bsObj.findAll(tag_to_find, href=re.compile("^(/ArticleList.nhn?)")): 이 부분 URL에 특정 패턴을 입력했을 뿐이다. 아래는 이전 소스이다. 비교해 보라. for link in bsObj.findAll(tag_to_find):
  • 9. 연습 3단계 : 링크에, 링크에, 링크에…링크로 들어가기 결과출력소스 지난 소스와 바뀐 부분에 주목할 점은, 1. 패턴과, (/ArticleList.nhn?|/ArticleRead.nhn?) 2. 들어갔던 링크에 다시 들어 갔는지 여부체크와, if link.attrs[attr_to_get] not in pages: 3. 재귀호출(recursive calling) 이다. if link.attrs[attr_to_get] not in pages: new_page = link.attrs[attr_to_get] print(new_page) pages.add(new_page) get_links(new_page) * 주의할 점 : Python에서 재귀호출은 1000번으로 제한되어 있다.
  • 10. 연습 4단계 : 링크 타고 들어가기만 하면 뭐하나? 결과출력소스 뭐하러 링크를 타고 들어갔나요? 거기 있는 글을 가져오려고 들어갔습니다. content = bsObj.find(id = id_to_find_for_content) 이렇게 하면, id=“tbody” 인 태그를 찾아서 그 안에 있는 컨텐츠를 가져옵니 다. 가져온 컨텐츠는 용도에 따라 가공해서 저장(DB, file 등)하 시면 됩니다. * 네이버카페의 몸글은 아래 태그 안에 있습니다. <div class="tbody m-tcol-c" id=“tbody"> ... </div>
  • 11. 연습 6단계 : Scrapy도 써보자! 각자 한 번 해보세요! (Scrapy는 python 3.x에서 아직 지원안함) 연습 5단계 : 연결된 다른 도메인까지 넘어가서 수집!