Beautiful Soup를 사용하여 간단한 웹 크롤러를 만드는 방법을 다루고 있습니다.
Python 3.6으로 코드를 작성하였습니다. 버전의 차이로 필요한 모듈이 달라질 수도 있습니다.
웹 크롤러(Web Crawler)는 웹문서, 이미지 등을 주기적으로 수집하여 자동으로 데이터베이스화하는 프로그램입니다. 웹 크롤러가 하는 작업을 웹 크롤링(Web Crawling)이라고 부릅니다.
보통 웹 크롤러를 사용하여 웹문서의 복사본을 생성합니다. 검색 엔진은 이렇게 생성된 데이터를 인덱싱하여 빠른 검색을 할 수 있도록 합니다.
웹 페이지의 내용을 가져오는 간단한 웹 크롤러를 만들어 보겠습니다.
시작하기 전에 requests와 beautifulsoup4 패키지를 설치해줘야 합니다.
pip install requests beautifulsoup4 |
1. 웹 문서 전체 가져오기
urlopen 함수를 사용하여 원하는 주소로부터 웹페이지를 가져온 후, BeautifulSoup 객체로 변환합니다.
BeautifulSoup 객체는 웹문서를 파싱한 상태입니다. 웹 문서가 태그 별로 분해되어 태그로 구성된 트리가 구성됩니다.
포함하는 태그가 부모가 되고 포함된 태그가 자식이 되어 트리를 구성하고 있습니다.
예를 들어 html 태그아래에 head와 body 태그가 존재하고 다시 head와 body 태그 아래에 하위 태그가 존재합니다.
파싱이란 일련의 문자열로 구성된 문서를 의미 있는 토큰(token)으로 분해하고 토큰으로 구성된 파스 트리(parse tree)를 만드는 것입니다.
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://www.naver.com") bsObject = BeautifulSoup(html, "html.parser") print(bsObject) # 웹 문서 전체가 출력됩니다. |
<!DOCTYPE doctype html> <html class="svgless" lang="ko"> <head> <meta charset="utf-8"/> <meta content="origin" name="Referrer"/> <meta content="text/javascript" http-equiv="Content-Script-Type"/> <meta content="text/css" http-equiv="Content-Style-Type"/> <meta content="IE=edge" http-equiv="X-UA-Compatible"/> <meta content="width=1100" name="viewport"/> <meta content="NAVER" name="apple-mobile-web-app-title"> <meta content="index,nofollow" name="robots"> <meta content="네이버 메인에서 다양한 정보와 유용한 컨텐츠를 만나 보세요" name="description"> <meta content="네이버" property="og:title"/> <meta content="https://www.naver.com/" property="og:url"/> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . </script> </body> </html> |
2. 타이틀 가져오기
태그로 구성된 트리에서 title 태그만 출력합니다.
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://www.naver.com") bsObject = BeautifulSoup(html, "html.parser") print(bsObject.head.title) |
<title>NAVER</title> |
3. 모든 메타 데이터의 내용 가져오기
웹문서에서 메타 데이터만 찾아서 content 속성값을 가져옵니다.
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://www.python.org/about") bsObject = BeautifulSoup(html, "html.parser") for meta in bsObject.head.find_all('meta'): print(meta.get('content')) |
None IE=edge Python.org The official home of the Python Programming Language Python.org yes black width=device-width, initial-scale=1.0 True telephone=no on false /static/metro-icon-144x144-precomposed.png #3673a5 #3673a5 The official home of the Python Programming Language Python programming language object oriented web free open source software license documentation download community website Python.org Welcome to Python.org The official home of the Python Programming Language https://www.python.org/static/opengraph-icon-200x200.png https://www.python.org/static/opengraph-icon-200x200.png https://www.python.org/about/ |
..
..
4. 원하는 태그의 내용 가져오기
find를 사용하면 원하는 태그의 정보만 가져올 수 있습니다.
예를 들어 www.python.org/about 에서 다음 태그의 content 속성값을 가져오려면..
<meta content="The official home of the Python Programming Language" name="description"/>
우선 웹문서에 있는 meta 태그 중 가져올 태그를 name 속성 값이 description인 것으로 한정합니다.
print (bsObject.head.find("meta", {"name":"description"})) |
<meta content="The official home of the Python Programming Language" name="description"/> |
meta 태그의 content 내용을 가져옵니다.
print (bsObject.head.find("meta", {"name":"description"}).get('content')) |
The official home of the Python Programming Language |
전체 소스코드입니다.
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://www.python.org/about") bsObject = BeautifulSoup(html, "html.parser") print (bsObject.head.find("meta", {"name":"description"}).get('content')) |
5. 모든 링크의 텍스트와 주소 가져오기
a 태그로 둘러싸인 텍스트와 a 태그의 href 속성을 출력합니다.
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://www.naver.com") bsObject = BeautifulSoup(html, "html.parser") for link in bsObject.find_all('a'): print(link.text.strip(), link.get('href')) |
C:\Users\webnautes\PycharmProjects\Python_Project\venv\Scripts\python.exe C:/Users/webnautes/PycharmProjects/Python_Project/1.py 뉴스스탠드 바로가기 #news_cast 주제별캐스트 바로가기 #themecast 타임스퀘어 바로가기 #time_square 쇼핑캐스트 바로가기 #shp_cst 로그인 바로가기 #account 네이버 / 네이버를 시작페이지로 http://help.naver.com/support/alias/contents2/naverhome/naverhome_1.naver 쥬니어네이버 http://jr.naver.com 해피빈 http://happybean.naver.com/main/SectionMain.nhn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 공지사항 //www.naver.com/NOTICE 서비스 전체보기 more.html 바로가기 https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8%EA%BD%83 프로젝트 꽃 https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8%EA%BD%83 다운받기 http://whale.naver.com/ 네이버웨일 http://whale.naver.com/ 크리에이터 http://www.navercorp.com/ko/service/creators.nhn 스몰비즈니스 http://www.navercorp.com/ko/service/business.nhn 비즈니스 파트너 안내 http://business.naver.com/guide.html 비즈니스 · 광고 http://business.naver.com/service.html 스토어 개설 https://sell.storefarm.naver.com/#/home/about 지역업체 등록 https://smartplace.naver.com/ 네이버 개발자센터 http://developers.naver.com 오픈 API https://developers.naver.com/docs/common/openapiguide/#/apilist.md/ 오픈소스 http://naver.github.io/ 네이버 D2 http://d2.naver.com/ 네이버 랩스 http://www.naverlabs.com/ 회사소개 http://www.navercorp.com/ 인재채용 http://recruit.navercorp.com/naver/recruitMain 제휴제안 https://www.navercorp.com/ko/company/proposalGuide.nhn 이용약관 /policy/service.html 개인정보처리방침 /policy/privacy.html 청소년보호정책 /policy/youthpolicy.html 네이버 정책 /policy/spamcheck.html 고객센터 https://help.naver.com/ NAVER Corp. http://www.navercorp.com/ |
관련 글
[Python/웹 크롤링(Web Crawling) 강좌] - 파이썬 웹 크롤링(Web Crawling) 강좌 - 2. 교보문고 베스트셀러 책이름, 저자, 가격 출력하기
[Python/웹 크롤링(Web Crawling) 강좌] - 파이썬 웹 크롤링(Web Crawling) 강좌 - 3. 네이버 베스트셀러 책이름, 저자, 가격 출력하기
[Python/웹 크롤링(Web Crawling) 강좌] - 웹크롤링 강좌 - 기상청의 동네예보 가져오기