[Python] Python으로 크롤링 해보기

[Python] Python으로 크롤링 해보기


크롤링이란?
  • 보통 웹 크롤러를 사용하여 웹문서의 복사본을 생성함
  • 검색 엔진은 이렇게 생성된 데이터를 인덱싱하여 빠른 검색을 할 수 있도록 함

시작하기 전에 requests와 beautifulsoup4 패키지를 설치해 줘야 함
  • beautifulsoup4는 크롤링에서 자주 사용하는 패키지
pip install requests beautifulsoup4


1. 웹 문서 전체 가져오기

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.naver.com")  
bsObject = BeautifulSoup(html, "html.parser")

print(bsObject) # 웹 문서 전체가 출력됩니다.
  1. urlopen :원하는 주소로부터 웹 페이지를 가져옴
  2. BeautifulSoup객체로 변환
    BeautifulSoup객체는 웹문서를 파싱한 상태
    웹문서가 태그별로 분해되어 태그로 구성된 트리가 존재

  • 출력 결과

<!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. 타이틀 가져오기

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>

댓글

이 블로그의 인기 게시물

[소프트웨어공학] NS(Nassi-Schneiderman) 차트

[운영체제] 파일의 구조(순차 파일, 직접 파일, 색인 순차 파일)

[운영체제] MLQ & MFQ