[python] #8. BeautifulSoup - find (2)

exoluse·2021년 10월 12일
0

python - web crawling

목록 보기
9/20
post-thumbnail

부모(들) 찾기 .find_parents

  1. .parents는 선택된 soup 의 부모 엘리먼트를 쭉~찾아 가는 기능이다.
html = """
<html><head><title>exoluse's velog</title></head>

<body>
    <div id="div1">
        <div id="div2">
            <p class="title"><b>exoluse's velog</b></p>
        </div>
    </div>
</body>

</html>

"""

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

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

print(selected1)
print(type(selected1))

<!-- 결과가 좀 많다. ResultSet을 좀 정리해 보겠다. -->
[
# 첫번째 부모
<div id="div2">
<p class="title"><b>exoluse's velog</b></p>
</div>, 

# 두번째 부모
<div id="div1">
<div id="div2">
<p class="title"><b>exoluse's velog</b></p>
</div>
</div>,

# 세번째 부모
<body>
<div id="div1">
<div id="div2">
<p class="title"><b>exoluse's velog</b></p>
</div>
</div>
</body>, 

# 네번째 부모
<html><head><title>exoluse's velog</title></head>
<body>
<div id="div1">
<div id="div2">
<p class="title"><b>exoluse's velog</b></p>
</div>
</div>
</body>
</html>, 

# 다섯번째 부모
<html><head><title>exoluse's velog</title></head>
<body>
<div id="div1">
<div id="div2">
<p class="title"><b>exoluse's velog</b></p>
</div>
</div>
</body>
</html>

]
<class 'bs4.element.ResultSet'>

부모 찾기 .find_parent


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

<body>
    <div id="div1">
        <div id="div2">
            <p class="title"><b>exoluse's velog</b></p>
        </div>
    </div>
</body>

</html>

"""

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

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

print(selected1)
print(type(selected1))

<!-- .find_parent 는 바로 상위 엘리먼트를 리턴한다. -->
<div id="div2">
<p class="title"><b>exoluse's velog</b></p>
</div>
<class 'bs4.element.Tag'>

아마 눈치 챘겠지만

기존에 다뤘던 기능들과 사실상 차이가 없다.

이걸 이렇게도 사용 가능하다
.parent
.parents
.find_parent()
.find_parents()
.next_sibling
.next_siblings
.find_next_sibling()
.find_next_siblings()
.previous_sibling
.previous_siblings
.find_previous_sibling()
.find_previous_siblings()

이전 BeautifulSoup 포스팅을 참조해 볼 수 있다.
https://velog.io/@exoluse/series/python-web-crawling

다음 포스팅에서는

셀렉터를 좀더 파보는 시간을 갖도록 하겠다. 끝

0개의 댓글