위키피디아 한국어 페이지에서 "평화의 소녀상"을 검색하면 다음과 같은 화면이 나타난다. 해당 URL을 requests 모듈을 이용하여 접속하고, html 소스를 가져온다. 

 

위키피디아 검색 결과 페이지

 

BeautifulSoup 클래스의 find( ) 메소드에 HTML 요소의 태그 이름(‘img’)을 전달하면, 해당 태그 부분을 찾아서 객체로 return 해준다. find( ) 명령은 HTML 문서에서 가장 처음으로 만나는 태그를 한 개 찾는다. 앞의 위키피디아 화면에서 가장 먼저 나오는 사진(img 태그)은 "주한 일본 대사관 앞 평화비"라는 설명이 붙어 있는 사진이다. 

 

"평화의 소녀상, 속초"라는 설명이 있는 사진을 나타내는 ‘img’ 태그를 선택하려면, attrs 매개변수에 해당 태그에만 해당하는 고유의 속성을 추가해야 한다. 개발자 도구를 이용하여 해당 태그를 확인할 수 있는데, alt 속성 값으로 이미지 소스 URL 값을 갖는다. 이 속성을 find( ) 메소드의 attrs 매개변수에 입력하는 방식으로, 특정 태그를 선택할 수 있다. 

 

import requests
from bs4 import BeautifulSoup

url = "https://ko.wikipedia.org/wiki/%ED%8F%89%ED%99%94%EC%9D%98_%EC%86%8C%EB%85%80%EC%83%81"
resp = requests.get(url)
html_src = resp.text

soup = BeautifulSoup(html_src, 'html.parser')
                    
photo_first = soup.find(name='img')
print(photo_first)
print("\n")

photo_sockcho = soup.find(name='img', attrs={'src':'//upload.wikimedia.org/wikipedia/commons/thumb/1/16/%ED%8F%89%ED%99%94%EC%9D%98%EC%86%8C%EB%85%80%EC%83%81%28Statute_of_Peace%29.jpg/220px-%ED%8F%89%ED%99%94%EC%9D%98%EC%86%8C%EB%85%80%EC%83%81%28Statute_of_Peace%29.jpg'})
print(photo_sockcho)

 

 

실행 결과는 다음과 같다. 두 개의 img 태그를 찾아서 내용을 확인할 수 있다. 이처럼, find( ) 메소드는 특정한 태그를 하나만 찾는 경우에 사용되고, 메모리 관리 측면이나 실행 시간에서 유리하다는 장점을 갖는다. 

 

<img alt="" class="thumbimage" data-file-height="3000" data-file-width="4000" decoding="async" height="173" src="//upload.wikimedia.org/wikipedia/commons/thumb/3/36/Japanese_Embassy_in_Seoul_and_watched_from_behind_a_bronze_statue_of_comfort_women.JPG/230px-Japanese_Embassy_in_Seoul_and_watched_from_behind_a_bronze_statue_of_comfort_women.JPG" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/3/36/Japanese_Embassy_in_Seoul_and_watched_from_behind_a_bronze_statue_of_comfort_women.JPG/345px-Japanese_Embassy_in_Seoul_and_watched_from_behind_a_bronze_statue_of_comfort_women.JPG 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/3/36/Japanese_Embassy_in_Seoul_and_watched_from_behind_a_bronze_statue_of_comfort_women.JPG/460px-Japanese_Embassy_in_Seoul_and_watched_from_behind_a_bronze_statue_of_comfort_women.JPG 2x" width="230"/>

 

 

<img alt="" class="thumbimage" data-file-height="2268" data-file-width="4032" decoding="async" height="124" src="//upload.wikimedia.org/wikipedia/commons/thumb/1/16/%ED%8F%89%ED%99%94%EC%9D%98%EC%86%8C%EB%85%80%EC%83%81%28Statute_of_Peace%29.jpg/220px-%ED%8F%89%ED%99%94%EC%9D%98%EC%86%8C%EB%85%80%EC%83%81%28Statute_of_Peace%29.jpg" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/1/16/%ED%8F%89%ED%99%94%EC%9D%98%EC%86%8C%EB%85%80%EC%83%81%28Statute_of_Peace%29.jpg/330px-%ED%8F%89%ED%99%94%EC%9D%98%EC%86%8C%EB%85%80%EC%83%81%28Statute_of_Peace%29.jpg 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/1/16/%ED%8F%89%ED%99%94%EC%9D%98%EC%86%8C%EB%85%80%EC%83%81%28Statute_of_Peace%29.jpg/440px-%ED%8F%89%ED%99%94%EC%9D%98%EC%86%8C%EB%85%80%EC%83%81%28Statute_of_Peace%29.jpg 2x" width="220"/>

 

앞서, 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