beautiful soup 모듈: 파이썬 코드를 복잡하게 작성하지 않아도 편하게 웹스크롤링을 할 수 있도록 웹스크롤링에 필요한 여러 함수들을 제공하는 웹스크롤링 전문 모듈임.
실습. 데이터 게시판에서 ecol.html 데이터를 c드라이브 data 폴더에 저장한 후 페이지 열어 확인하기
**div 태그 → li 태그 → div 태그로 상위 태그에서 하위 태그로 내려오면서 텍스트에 접근하면 됨. 그리고 그 텍스트를 긁어오면 됨. html 문서를 보면 class 와 id 가 있는 것은 특정 부분의 위치정보라고 생각하면 됨. id 는 class 와는 달리 값이 중복되지 않는 유니크한 값으로 구성됨.
실습. ecol.html 문서를 웹스크롤링 하기 편하도록 beautiful soup 모듈에서 사용할 수 있도록 파싱(parsing) 하기
- 파싱(parsing) → 사람이 알아볼 수 있는 언어를 기계가 알아볼 수 있는 언어로 변환하는 것 - beautiful soup 모듈이 사용할 수 있도록 파싱 한다는 것 → html 문서를 beautiful soup 모듈안에서 모듈함수를 이용해 자유롭게 html 문서를 다룰 수 있는 상태로 만들겠다는 것
from bs4 import BeautifulSoup
f = open('c:\\data\\ecol.html')
soup = BeautifulSoup(f, 'html.parser') # html을 BeautifulSoup 모듈로 파싱
print(soup)
실습. eco.html 문서에서 class 이름이 name 에만 접근해서 그 주변 데이터를 긁어오시오.
from bs4 import BeautifulSoup
f = open('c:\\data\\ecol.html')
soup = BeautifulSoup(f, 'html.parser')
result = soup.find_all(class_ = 'name')
실습. 위 result 리스트 안에 있는 요소들을 for loop 문을 이용해서 하나씩 뽑아서 출력하시오.
from bs4 import BeautifulSoup
f = open('c:\\data\\ecol.html')
soup = BeautifulSoup(f, 'html.parser')
result = soup.find_all(class_ = 'name')
for i in result:
print(i)
실습. 위의 결과에서 html 코드 말고 텍스트에만 해당하는 코드를 출력하시오.
from bs4 import BeautifulSoup
f = open('c:\\data\\ecol.html')
soup = BeautifulSoup(f, 'html.parser')
result = soup.find_all(class_ = 'name')
for i in result:
print(i.text)
문제. ecol.html 문서에서 숫자에 해당하는 부분만 긁어와서 출력하시오.
from bs4 import BeautifulSoup
f = open('c:\\data\\ecol.html')
soup = BeautifulSoup(f, 'html.parser')
result = soup.find_all(class_ = 'number')
for i in result:
print(i.text)
마지막 문제. 위의 코드들을 가지고 아래의 결과를 출력하시오
from bs4 import BeautifulSoup
f = open('c:\\data\\ecol.html')
soup = BeautifulSoup(f, 'html.parser')
name = []
number = []
result1 = soup.find_all(class_ = 'name')
result2 = soup.find_all(class_ = 'number')
for i in result1:
name.append(i.text)
for i in result2:
number.append(i.text)
for name, number in zip(a, b):
print(f"{name} 은/는 {number} 마리가 있습니다.")