하얀설표 블로그




bs4.BeautifulSoup .text와 .get_text()뭐가 다를까?(what differences between .text and .get_text())





( 수정됨)


미리보는 결론

.text는 .get_text()와 .getText()의 모두 같은 결과를 주는 명령어다.

설명

bs4 모듈의 .get_text(), .getText(), .text 명령 모두 element.py에서 정의되고 있는다.
bs4의 배포 사이트에서도 확인할 수 있다.

코드에서 get_text()가 정의된 바로 다음줄을 보면 다음과 같이 getText = get_text, text = property(get_text)라고 되어있는 것을 알 수 있다.

아마도 이전 버전에서는 .getText()로 제공되었다가 .get_text()로 변경하면서 이전 버전 사용자를 배려한 것으로 보인다.
실행 명령은 3개지만, 모두 .get_text()에서 return한 결과값을 가져오기 때문에 모두 같은 결과를 얻게 된다.

.text는 프로퍼티를 통해 만들어진 getter인데, 이에 관한 내용은 이전에 다룬 적이 있으므로 링크로 대체한다.

# bs4.element.py
class PageElement(object):
    (생략)
    def setup(self, parent=None, previous_element=None, next_element=None,
              previous_sibling=None, next_sibling=None):
        (생략)
    def format_string(self, s, formatter):
        (생략)
    def formatter_for_name(self, formatter):
        (생략)
    @property
    def _is_xml(self):
        (생략)
    def _all_strings(self, strip=False, types=default):
        (생략)
    @property
    def stripped_strings(self):
        (생략)
    def get_text(self, separator="", strip=False,
                 types=default):
        return separator.join([s for s in self._all_strings(
                    strip, types=types)])
    getText = get_text
    text = property(get_text)
    (생략)


공감 : 0







white.seolpyo.com