[python] #7. BeautifulSoup - find (1)

exoluse·2021년 10월 12일
0

python - web crawling

목록 보기
8/20
post-thumbnail

.find_all 과의 차이점?

  1. 먼저 find_all 을 다시 보도록 하자.
from bs4 import BeautifulSoup

html = """
<html><head><title>exoluse's velog</title></head>

<body>
<p class="title"><b>exoluse's velog</b></p>
<b class="vel" meta_tag="python" metaTag="python">exoluse's velog</b>
</body>

</html>

"""

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

selected1 = soup.find_all("body")

print(selected1)
print(type(selected1))

<!-- 결과 : ResultSet 이 리턴되었다. -->
[<body>
<p class="title"><b>exoluse's velog</b></p>
<b class="vel" meta_tag="python" metatag="python">exoluse's velog</b>
</body>]
<class 'bs4.element.ResultSet'>
  1. 그럼 find 는?
from bs4 import BeautifulSoup

html = """
<html><head><title>exoluse's velog</title></head>

<body>
<p class="title"><b>exoluse's velog</b></p>
<b class="vel" meta_tag="python" metaTag="python">exoluse's velog</b>
</body>

</html>

"""

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

selected1 = soup.find("body")

print(selected1)
print(type(selected1))

<!-- 결과 : 리턴 타입이 태그 이다. -->
<body>
<p class="title"><b>exoluse's velog</b></p>
<b class="vel" meta_tag="python" metatag="python">exoluse's velog</b>
</body>
<class 'bs4.element.Tag'>

find_all 과 find 의 결과가 다르다...

find라고 용법이 아예 다른 것은 아니다.

  1. find 를 이용하여 class 속성값이 title 인 p 태그 구하기
html = """
<html><head><title>exoluse's velog</title></head>

<body>
<p class="title"><b>exoluse's velog</b></p>
<b class="vel" meta_tag="python" metaTag="python">exoluse's velog</b>
</body>

</html>

"""

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

selected1 = soup.find("p", class_="title")

print(selected1)
print(type(selected1))

<!-- 결과 : 예상했던 '그' 결과가 나온다. -->
<p class="title"><b>exoluse's velog</b></p>
<class 'bs4.element.Tag'>
  1. find 를 이용하여 body 태그 밑의 b 태그 중 vel 이라는 속성값을 가지는 태그 구하기

html = """
<html><head><title>exoluse's velog</title></head>

<body>
<p class="title"><b>exoluse's velog</b></p>
<b class="vel" meta_tag="python" metaTag="python">exoluse's velog</b>
</body>

</html>

"""

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

selected1 = soup.find("body").find("b", "vel")

print(selected1)
print(type(selected1))

<!-- 결과 : soup.find_all("b", "vel")[0] 과 같은 결과가 리턴된다. -->
<b class="vel" meta_tag="python" metatag="python">exoluse's velog</b>
<class 'bs4.element.Tag'>

find는 중첩 사용이 가능하다.

html = """
<html><head><title>exoluse's velog</title></head>

<body>
<p class="title"><b>exoluse's velog</b></p>
<b class="vel" meta_tag="python" metaTag="python">exoluse's velog</b>
</body>

</html>

"""

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

selected1 = soup.find("html").find("head").find("title")

print(selected1)
print(type(selected1))

<!-- 결과 : html 밑의 head 밑의 title 태그가 리턴된다. -->
<title>exoluse's velog</title>
<class 'bs4.element.Tag'>

결론

.find_all 과 용법은 비슷하다. 리턴되는 데이터 타입이 ResultSet, Tag 로 다를 뿐...

0개의 댓글