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, 'html5lib')
soup.find('head')
<head><title>The Dormouse's story</title></head>

여기까지는 기본인데, 다음은 될까, 안될까??

soup.find('head').find('head')
None(실은 아무 결과도 안나온다)

안되니까 썼겠지.

type(soup.find('head'))
bs4.element.Tag
soup.find('head').name
'head'

BeautifulSoup 의 find/find_all 은, 현재 위치가 Tag(bs4.element.Tag) 인 경우, 자신 바로 아래, 즉 Descendants 에서 검색을 한다.
만약, soup.find('head').find('head') 이게 된다면, 뭔가 심각한 오류가 발생할 수도 있다.

다만, 현재 위치(객체)가 BeautifulSoup 자체인 경우, 최초 Tag 부터 검색이 된다.
즉,

type(soup)
bs4.BeautifulSoup
soup.find('html')
<html><head><title>The Dormouse's story</title></head>
~~~~ 어쩌고 저쩌고...

이렇게는 사용 가능하다.

Author: 아무도안

안녕하세요. 글 남겨주셔서 고맙습니다.