앞서, requests 모듈을 사용하여 웹 페이지를 요청하고, 응답 객체의 text 속성을 통해 HTML 소스코드를 얻는 과정을 살펴보았다.

 

2019/08/01 - [웹 스크래핑 (Web Scraping)] - [5] 파이썬 웹 스크래핑 - requests 모듈, HTML 소스코드 확인

 

 

HTML 태그와 같이 요소별로 구분하여 HTML 문서를 해석하는 작업을 파싱이라고 부른다. HMTL 소스코드를 파싱(parsing)하고 원하는 정보를 추출하기 위해 BeautifulSoup 라이브러리를 사용한다. 파이썬 클래스로 정의되어 있고, 윈도 명령 프롬프트 또는 터미널 창에서 “pip install beautifulsoup4”를 입력하여 설치한다. 

 

BeautifulSoup 클래스는 매개변수로 전달받은 HTML 소스코드를 해석하여 BeautifulSoup 객체를 생성한다. 이 때, HTML을 파싱(해석)하는 적절한 구문 해석기(파서, parser)를 함께 입력해야 한다. 파서에는 "html.parser", "lxml" 등이 자주 사용된다. (주: XML 구문 해석을 위해서는 "xml" 파서를 따로 설치해서 사용한다.)

 

1) requests 모듈로 html 소스코드 얻기

import requests
from bs4 import BeautifulSoup

url = "https://en.wikipedia.org/wiki/Main_Page"
resp = requests.get(url)
print(resp)
print("\n")

html = resp.text
print(html[:300])
print("\n")

 

requests 모듈의 get( ) 함수의 요청에 웹 서버가 정상 응답하는 경우 코드 200의 값을 갖는다. 응답 객체의 text 속성을 html 변수에 저장하고 일부를 출력하면 html 소스코드를 확인할 수 있다. 

 

<Response [200]>

 

 

<!DOCTYPE html>

<html class="client-nojs" lang="en" dir="ltr">

<head>

<meta charset="UTF-8"/>

<title>Wikipedia, the free encyclopedia</title>

<script>document.documentElement.className=document.documentElement.className.replace(/(^|\s)client-nojs(\s|$)/,"$1client-js$2");RLCONF={"wgCanonicalNamespace

 

 

 

2) html 소스코드를 BeautifulSoup 클래스 객체로 변환하기

soup = BeautifulSoup(html, 'html.parser')
print(type(soup))
print("\n")                 
print(soup.head)
print("\n")
print(soup.body)
print("\n")

 

다음에는 html 문자열을 BeautifulSoup 클래스 객체로 변환한다. type( ) 함수로 soup 객체를 확인하면, BeautifulSoup 클래스 객체라는 것을 알 수 있다. 여기서 soup 객체의 head 부분을 따로 지정할 수 있는데, 다음 실행결과와 같이 <head> 태그 부분이 출력된다. 마찬가지로 <body> 태그 부분을 따로 선택할 수도 있다. 

 

<class 'bs4.BeautifulSoup'>

 

 

<head>

<meta charset="utf-8"/>

<title>Wikipedia, the free encyclopedia</title>

<script>document.documentElement.className=document.documentElement.className.replace(/(^|\s)client-nojs(\s|$)/,"$1client-js$2");RLCONF={"wgCanonicalNamespace":"","wgC ... <중략>...

 

 

<body class="mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Main_Page rootpage-Main_Page skin-vector action-view">

<div class="noprint" id="mw-page-base"></div>

<div class="noprint" id="mw-head-base"></div>

<div class="mw-body" id="content" role="main">

<a id="top"></a>

<div class="mw-body-content" id="siteNotice"><!-- CentralNotice --></div>

<div class="mw-indicators mw-body-content">

</div>  

<h1 class="firstHeading" id="firstHeading" lang="en">Main Page</h1>

<div class="mw-body-content" id="bodyContent">

<div class="noprint" id="siteSub">From Wikipedia, the free encyclopedia</div>

<div id="contentSub"></div>

<div id="jump-to-nav"></div>  ... <이하 생략>...

 

3) BeautifulSoup 클래스 속성 확인하기

print(soup.title)
print(soup.title.name)
print(soup.title.string)

 

<title> 태그를 먼저 선택해서 출력하면 태그의 문자열까지 전부 확인할 수 있다. 여기서 하위 속성인 name을 이용하면, 태그명을 선택할 수 있고, string 속성을 이용하면 문자열을 따로 추출할 수도 있다.

 

<title>Wikipedia, the free encyclopedia</title>

title

Wikipedia, the free encyclopedia

+ Recent posts