Notice
Recent Posts
Recent Comments
Link
터칭 데이터
파싱과 스크래핑의 기본, BeautifulSoup 본문
In [18]:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
2-2. 파이썬의 HTML Parser, BeautifulSoup¶
- HTML 분석기인 BeautifulSoup에 대해서 알아봅시다.
BeautifulSoup 라이브러리¶
지난 실습들에서 저희는 requests
모듈을 이용해서 HTTP 요청을 보내고, 이 응답을 받아 여러 요소를 살펴보았습니다.
그런데, res.body
를 해보았을 때 문제점이 있었습니다. 바로 해당 내용이 아주 긴 텍스트로 와서 분석하기 힘들다는 것이 바로 그것인데요,
저희가 원하는 요소만을 가져올 수 있으면 얼마나 좋을까요?
이를 가능하도록 HTML 코드를 분석해주는, HTML Parser를 사용할 수 있습니다. 그 중에서 가장 유명한 것이 바로 오늘 저희가 사용할 BeautifulSoup4
입니다.
우선, 이를 사용하기 위해서 pip
를 사용해 다운로드를 받아봅시다.
Tip:
%
를 이용해서 노트북(.ipynb) 환경에서 터미널 코드를 실행할 수 있습니다.
In [ ]:
%pip install bs4
설치를 다 진행했다면, 이제 BeautifulSoup4
모듈을 사용할 준비가 되었습니다.
이제 이를 바탕으로 HTTP 코드를 분석해 원하는 정보만을 얻으러 가볼까요?
BeautifulSoup 객체 만들기¶
In [2]:
import requests
res = requests.get("https://www.example.com")
res.text
Out[2]:
'<!doctype html>\n<html>\n<head>\n <title>Example Domain</title>\n\n <meta charset="utf-8" />\n <meta http-equiv="Content-type" content="text/html; charset=utf-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1" />\n <style type="text/css">\n body {\n background-color: #f0f0f2;\n margin: 0;\n padding: 0;\n font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;\n \n }\n div {\n width: 600px;\n margin: 5em auto;\n padding: 2em;\n background-color: #fdfdff;\n border-radius: 0.5em;\n box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);\n }\n a:link, a:visited {\n color: #38488f;\n text-decoration: none;\n }\n @media (max-width: 700px) {\n div {\n margin: 0 auto;\n width: auto;\n }\n }\n </style> \n</head>\n\n<body>\n<div>\n <h1>Example Domain</h1>\n <p>This domain is for use in illustrative examples in documents. You may use this\n domain in literature without prior coordination or asking for permission.</p>\n <p><a href="https://www.iana.org/domains/example">More information...</a></p>\n</div>\n</body>\n</html>\n'
In [3]:
# BeautifulSoup 객체를 만든다.
# 첫번째 인자는 response의 body를 텍스트로
# 두번째 인자로는 html로 분석한다고 명시
from bs4 import BeautifulSoup
soup = BeautifulSoup(res.text, "html.parser")
In [5]:
# 주피터 상에서는 print()로 출력해야 들여쓰기가 적용된다.
print(soup.prettify())
<!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>
In [6]:
# title 태그 가져오기
soup.title
Out[6]:
<title>Example Domain</title>
In [7]:
# head 태그 가져오기
soup.head
Out[7]:
<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>
In [10]:
# body 태그 가져오기
soup.body
Out[10]:
<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>
In [9]:
# h1 태그 요소 하나 찾기
soup.h1
soup.find("h1")
Out[9]:
<h1>Example Domain</h1>
Out[9]:
<h1>Example Domain</h1>
In [13]:
# p 태그 요스'들' 찾기
output = soup.find_all("p")
output[0]
output[1]
Out[13]:
<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>
Out[13]:
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
In [16]:
# 태그 이름 가져오기
h1 = soup.find("h1")
print(h1)
h1.name
<h1>Example Domain</h1>
Out[16]:
'h1'
In [15]:
# 태그 내용 가져오기
h1.text
Out[15]:
'Example Domain'
'웹 스크래핑(Web scraping)' 카테고리의 다른 글
Selenium의 기초 WebDriver (0) | 2023.10.26 |
---|---|
요청시 헤더의 수정과 페이지네이션(Pagination) (0) | 2023.10.25 |
스크래핑할 요소의 타게팅 - ID & Class (0) | 2023.10.25 |
스크래핑할 요소의 타게팅 - 태그 (0) | 2023.10.25 |
requests 라이브러리 (0) | 2023.10.24 |