- BeautifulSoup - 파이썬 웹 크롤링 라이브러리
- BeautifulSoup 기본 사용
- Requests 기본 사용
- 네이버 뉴스 제목 가져오기
- 삼성전자 주식 일별시세 가져오기
- BBC 뉴스 검색 결과 가져오기
- Python Tutorial
- NumPy Tutorial
- Matplotlib Tutorial
- PyQt5 Tutorial
- BeautifulSoup Tutorial
- xlrd/xlwt Tutorial
- Pillow Tutorial
- Googletrans Tutorial
- PyWin32 Tutorial
- PyAutoGUI Tutorial
- Pyperclip Tutorial
- TensorFlow Tutorial
- Tips and Examples
BeautifulSoup 기본 사용¶
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
예제로 사용할 html 문서(html_doc)가 있습니다. (BeautifulSoup 공식 문서 참고)
soup.prettify()¶
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
<head>
<title>
The Dormouse's story </title> </head> <body>
<p class="title">
<b>
The Dormouse's story
</b>
</p>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>
,
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>
and
<a class="sister" href="http://example.com/tillie" id="link3">
Tillie
</a>
; and they lived at the bottom of a well.
</p>
<p class="story">
...
</p>
</body>
</html>
soup.prettify()
를 출력해보면 html 문서의 계층 구조를 알기 쉽게 보여줍니다.
soup.a¶
print(soup.a)
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
a 태그를 반환합니다.
soup.find_all()¶
print(soup.find_all('a'))
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
모든 a 태그를 리스트 형태로 반환합니다.
soup.find()¶
soup.find(id="link3")
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
id가 ‘link3’인 태그를 반환합니다.
get()¶
for link in soup.find_all('a'):
print(link.get('href'))
http://example.com/elsie
http://example.com/lacie
http://example.com/tillie
href 속성을 반환합니다.
get_text()¶
print(soup.get_text())
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.
...
html 문서 안에 있는 텍스트를 반환합니다.
이전글/다음글
다음글 : Requests 기본 사용