1. Install BeautifulSoup
!pip install b4
- 외장 라이브러리 때문에 따로 설치가 필요하다.
from bs4 import BeautifulSoup
2. Run BeautifulSoup
- 단순히 title 태그를 가져오는 예시를 함께 봐보자.
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.example.com")
bs = BeautifulSoup(html.read(),'html.parser')
bs.title
- 좀 더 자세히 알아보면,
- urlopen("http://www.example.com")을 통해, www.example.com에 HTTP 요청을 보내고,
- HTML을 받아온다. (HTML을 한번 자세히 살펴보자.)
<!DOCTYPE html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-type"/>
<meta content="width=device-width, initial-scale=1" name="viewport"/>
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 2em;
background-color: #fdfdff;
border-radius: 0.5em;
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}
@media (max-width: 700px) {
div {
margin: 0 auto;
width: auto;
}
}
</style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
- 우리가 불러온 <title> 태그는 bs객체에서 (html --> head --> title) 이렇게 형성되어있다.
bs = BeautifulSoup(html.read(),'html.parser')
- 해당 함수를 조금 자세히 살펴보자,
- BeatifulSoup(HTML 문자열, 사용할 Parser) cf) 어떤 parser를 선택하든 상관없다.
- Parser는 컴퓨터가 문장을 토큰 단위로 분류하고 구문을 분석하는 프로그램을 의미한다.
- 요즘 많이 쓰이는 parser를 소개하자면, lxml이 있다.
- 이 lxml을 사용하기 위해선 따로 install해야한다.
!pip install lxml
bs = BeautifulSoup(html.read(), 'lxml')
- lxml은 parser에비해, messy하거나, 잘못된 HTML을 더 잘 분석한다는 장점이 존재한다.
3. Connecting Reliably and Handling Exceptions
- 일반적으로 HTTP를 보낼때, 오류가 뜨는 이유는 크게 두가지가 존재한다.
i) 서버에서 페이지를 찾을 수 없구나 검색하는 동안 오류가 발생할 때 (HTTPError)
ii) 서버를 전혀 찾을 수 없을 때 (URLError)
3.1. HTTPError
- 다음과 서버는 접속이 되지만 존재하지 않는 사이트를 접속하고자 해보자.
html = urlopen("http://www.example.com/None")
- 이 때, urlopen 함수는 HTTPError를 일으키게 된다.
- 보통 예외처리는 다음처럼 처리하게 된다.
from urllib.request import urlopen
from urllib.error import HTTPError
try:
html = urlopen("http://www.example.com/None")
except HTTPError as e:
print(e)
else:
#~~~
print('-')
3.2. URLError
- 서버 자체가 없는 경우를 확인해보자
html = urlopen("http://www.examp1e.com")
from urllib.request import urlopen
from urllib.error import HTTPError,URLError
try:
html = urlopen("http://www.examp1e.com/None")
except HTTPError as e:
print(e)
except URLError as e:
print(e)
else:
#~~~
print('-')
3.3. AttributeError
- 서버에서 성공적으로 HTML을 가져왔어도, 없는 tag를 가져오게 되면, AttributeError가 발생하게 된다.
- 물론, 첫 없는 tag를 가져오게 되면 None으로 반환된다.
- 여기서 한번더 하위 tag를 지정하면 AttributeError 발생하게 된다.
- 즉, 예외처리를 두번 설정해줘야한다는 의미가 될 수 있다.
try:
Nonetag = bs.no.one
except AttributeError as e:
print("Tag가 없습니다.")
else:
if Nonetag == None:
print("Tag가 없습니다.")
else:
#~~~
- HTTPError, URLError, AttributeError을 모두 예외처리해주면 보다 편하게 Web Scarpping을 할 수 있다.
'DS Study > Web Scraping' 카테고리의 다른 글
[Web Scraping] [3.2] Regular Expressions (0) | 2025.03.26 |
---|---|
[Web Scraping] [3.1] BeautifulSoup (HTML Parsing) (0) | 2025.03.26 |
[Web Scraping] [2.1] urllib (파이썬 라이브러리) (0) | 2025.03.25 |
[Web Scraping] [1.2] HTML,CSS (0) | 2025.03.24 |
[Web Scraping] [1.1] OSI 7 Layer (1) | 2025.03.24 |