Ex 01. 크롤링의 기초
import requests as req
#1. 특정 사이트 정보를 요청
res = req.get("https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&ssc=tab.nx.all&query=싱크홀&oquery=기아타이거즈&tqi=i%2B4apwqVN8Vsst7Nczossssssd4-342687")
#2. 수많은 응답속에 텍스트정보만 추출 = HTML 데이터
res.text
#3. String데이터를 컴퓨터가 이해할 수 잇도록 HTML로 변환 (parsing)
from bs4 import BeautifulSoup as bs
soup = bs(res.text,"lxml")
#4. 특정 태그를 수집
news = soup.select("a.news_tit")
#5. HTML데이터에서 사람이 필요한 컨텐츠(글자)만 저장시킨다.
text = []
for i in news :
text.append(i.text)
text
프로세스
1) 데이터 요청
2) 데이터 변환
3) 요소 수집
4) 요소 가공(컨텐츠,속성) 필요한 데이터만 추출
5) 가공된 데이터 활용(시각화, 파일로 저장, 인공지능 데이터 활용...)
Ex02. 멜론차트
import requests as req
from bs4 import BeautifulSoup as bs
#1. 사이트 정보 요청
req.get("https://www.melon.com/chart/index.htm")
browser = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"}
res = req.get("https://www.melon.com/chart/index.htm",headers = browser)
#2. HTMl 데이터로 변환
soup = bs(res.text, "lxml")
#3 가수 100명, 노래 100곡 수집 = 요소 수집
title = soup.select("div.ellipsis.rank01 > span > a")
singer = soup.select("div.ellipsis.rank02 > span > a")
#4. 데이터 검증(데이터의 개수, 중복여부)
len(title)