https://www.crummy.com/software/BeautifulSoup/bs4/doc/

  1. beautifulsoup4 라이브러리 설치
$ pip install beautifulsoup4
from bs4 import BeautifulSoup

with open("html_sample.html", "r", encoding="utf-8") as f:
    text = f.read()
    print(type(text))  # <class 'str'>

# html을 파싱해서 구조화된 데이터 추출
# html.parser : python에 내장되어 있는 라이브러리
bs = BeautifulSoup(text, "html.parser")
print(type(bs))  # <class 'bs4.BeautifulSoup'>

def find_tag():
    # find() : 조건에 맞는 태그 중 첫번째 태그를 리턴
    tag = bs.find("li")
    
    # find_all() : 조건에 맞는 모든 태그를 리스트로 리턴
    tags = bs.find_all("li")

		# id로 태그 탐색
    section_tag = bs.find_all("section", {"id": "section1"})

    return {"tag": tag, "tags": tags, "section_tag": section_tag}

result = find_tag()

print(result["tag"])
print(type(result["tag"]))  # <class 'bs4.element.Tag'>

print(result["tags"])
print(type(result["tags"]))  # <class 'bs4.element.ResultSet'>

print(result["section_tag"])

❓ with open 안에 선언한 bs 변수를 find_tag() 함수에서 사용되는게 어떻게 가능 한가?

Group 237709.png

with open(...) as f: 블록 안에서 정의한 bs전역 변수로 잡힌다.

전역 변수로 사용 가능 예