https://www.crummy.com/software/BeautifulSoup/bs4/doc/
$ 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"])
def), 람다(lambda), 클래스(class), 모듈 단위.if, for, while, with, try 등 제어문 블록.
⇒ with open(...) as f: 블록 안에서 정의한 bs가 전역 변수로 잡힌다.