MoonNote

반응형
     

 

 

내용 찾기(Find Function)

find(), find_all()

 

BeautifulSoup에서 지정된 조건에 해당하는 내용을 찾아주는 함수

 

예제(Example)

<Example 01>

 html_doc 문서(더미 데이터)를 생성하고 find 함수로 a 태그를 검색 (find 함수의 경우 1개만 검색)

from bs4 import 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>
"""

soup=BeautifulSoup(html_doc, "html.parser")

print(soup.find("a"))

Result

<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

 

<Example 02>

 Example 01의 코드에서 함수만 find_all로 변경

from bs4 import 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>
"""

soup=BeautifulSoup(html_doc, "html.parser")

print(soup.find_all("a"))

Result

[<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>]

BeautifulSoup4 함수들

 

 

 

 

 

 

 

 

※ 이 글이 도움이 되었다면 "👆🏻구독"과 "🤍공감" 버튼을 클릭해주세요. 클릭 한번이 글 쓰는데 큰 힘이 됩니다.

공유하기

facebook twitter kakaoTalk kakaostory naver band