[항해99_chatGPT 웹개발 완전정복] 2-3주차 강의 TIL
jQuery
간편한 자바스크립트 코드 라이브러리(import 해야함). html 뼈대를 선택해서 쉽게 조작할 수 있음.
사용방법
1. jQuery import 하기 head 태그에 꼭 넣기
<script src ="jquery-3.6.4.min.js "></script >
<script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js "></script >
2. jQuery에서는 id 값을 통해 특정 버튼/인풋박스/div/.. 등을 가리키게 됨.
<script >
function checkResult (){
let word ='사과 '
$('#q1 ').text (word)
}
</script >
$(‘#id값’).text( ) : 함수 실행하면 아이디가 q1인 태그에 word를 넣는 코드임. (교체의 느낌)
.append( ) : 추가하는 메소드 (추가)
.empty( ) : 삭제하는 메소드
.attr( ) : - 가져오기 : $(‘div’).attr(‘class’); div요소의 class 속성의 값 가져오기
.attr( ) : - 추가: $(‘h1’).attr(‘title’, ‘Hello); h1요소에 title속성 추가하고, 속성의 값은 Hello한다.
Fetch
짧은 코드로 요청을 보내고(GET), 받아 올 수 있음(POST).
아래와 같은 패치 기본 골격을 html파일 중 script 태그 내에 넣어준다. 이제 이 골격과 함께라면 두려울 것이 없다.
fetch("여기에 URL을 입력") // 이 URL로 웹 통신을 요청한다. 괄호 안에 다른 것이 없다면 GET!
.then(res => res.json()) // 통신 요청을 받은 데이터는 res라는 이름으로 JSON화 한다
.then(data => {
console.log(data) // 개발자 도구에 찍어보기
}) // JSON 형태로 바뀐 데이터를 data라는 이름으로 붙여 사용한다
(GET) URL에 웹 통신 요청 보냄(url이 들어있는 괄호안에 url밖에 없으면 기본상태 get임) → (여기서부터 POST) 요청받은 데이터는 res 변수 이용 → res를 JSON형태로 바꿔 → JSON자료를 data:{ }에 넣겠음(요청받아 객체로 변경)
Fetch 이용해 데이터 처리
JSON으로 받아온 데이터에서 원하는 값 찾아 객체와 배열 형태로 값을 찾는다.
<script >
fetch ("http://spartacodingclub.shop/sparta_api/seoulair ") // 이 URL로 웹 통신을 요청한다. 괄호 안에 다른 것이 없다면 GET!
.then (res =>res .json ()) // 통신 요청을 받은 데이터는 res라는 이름으로 JSON화 한다
.then (data =>{
let rows =data ['RealtimeCityAir ']['row ']
rows .forEach (row =>{
console .log (row ) //반복문을 이용하여 요소들을 꺼내 사용한다.
});
})
</script >
Fetch + jQuery
<body>
<div class ="footer ">
<p id ="author "></p >
<p id ="content "></p >
<script>
let weather_url ="http://spartacodingclub.shop/sparta_api/weather/seoul ";
fetch (weather_url )
.then (res =>res .json ())
.then (data =>{
let temp =data ['temp ']
let icon_url =data ['icon ']
$('#weather-msg ').text (`${temp }ºC `)
$('#weather-icon ').attr ('src ',icon_url )
})
</scrip>
</body>
조건에 따라 css를 바꾸고 싶을 때 예시
<script >
if (gu_mise >35 ) {
temp_html =`<li class="bad">${gu_name } : ${gu_mise }</li>`
}else {
temp_html =`<li>${gu_name } : ${gu_mise }</li>`
}
$('#q1_name ').append (temp_html)
</script >
<style >
.bad {
color : red ;
}
</style >
ㄴ 기존 li 태그를 기준으로 해당 조건에 해당하는 태그는 class명을 추가하는 코드를 넣고, 추가된 class에 대한 CSS를 변경해주면 됨.
웹 스크래핑(크롤링)_파이썬
1. API사이트 → 크롤링
requests 패키지: pip install requests
미세먼지 API를 웹 브라우저 주소창에 넣는 것처럼 데이터를 불러와서 가져오는 기능(웹 스크래핑(크롤링): API로 제공되어지는 데이터가 아니더라도 웹 내용을 무단으로 긁어올 수 있음_법에 저촉되는 경우가 있다하니 아무거나 긁어오면 안된다.)
import requests # requests 라이브러리 설치 필요
r =requests .get ('http://spartacodingclub.shop/sparta_api/seoulair ')
rjson =r.json ()
rows =rjson ['RealtimeCityAir']['row']
for row in rows :
gu_name =row ['MSRSTE_NM']
gu_mise =row ['IDEX_MVL']
print (gu_name ,gu_mise )
2. API사이트X → 크롤링
Beautiful Soup 패키지: pip install requests bs4
Beautiful Soup | 웹 페이지의 HTML 구조를 분석하고, 정보를 추출하는 도구 |
requests | 웹 페이지에 접속하여 데이터를 가져오는 도구 |
# 멜론뮤직 스크래핑
from bs4 import BeautifulSoup
import requests
# bs4 시작코드
'''
스크래핑 하고 싶은 주소를 url에 넣어주세요
'''
url ="https://www.melon.com/chart/"
headers ={'User-Agent ':'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36 '}
data =requests .get (url ,headers =headers )
soup =BeautifulSoup (data .text ,'html.parser ')
#실행 시에는 터미널에 python 파일명.py (엔터)하면 됨.
#bs4
# select / select_one
# 선택자를 사용하는 방법 (copy selector)
soup.select ('태그명 ')
soup.select ('.클래스명 ')
soup.select ('#아이디명 ')
soup.select ('상위태그명 >하위태그명 >하위태그명 ')
soup.select ('상위태그명.클래스명 >하위태그명.클래스명 ')
# 태그와 속성값으로 찾는 방법
soup.select ('태그명[속성="값"]')
# 한 개만 가져오고 싶은 경우
soup.select_one ('위와 동일 ')
# find / find_all
#태그 이름만 특정한 경우
soup.fint('태그명')
soup.fint('class'='클래스명')
soup.fint(attrs = {'class':'클래스명'})
soup.find('태그명', 'class'='example')
find보다 find는 사용하려면 여러번 써줘야해서 select를 쓰는게 더 유용함.
ㄴ .클래스이름 > html태그 사용가능: 클래스이름에 해당하는 html태그 안의 html태그로 골라잡을 수 있음.( html태그, 아이디, 클래스 이름도 가능)
멜론의 탑100을 불러와보자.
# 멜론뮤직 스크래핑
from bs4 import BeautifulSoup
import requests
# bs4 시작코드
'''
스크래핑 하고 싶은 주소를 url에 넣어주세요
'''
url = "https://www.melon.com/chart/"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get(url, headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
trs = soup.select('tbody > tr')
for tr in trs:
rank = tr.select_one('.rank').text
title = tr.select_one('.rank01 > span > a').text
artist = tr.select_one('.rank02 > a').text
img_url = tr.select_one('img')['src']
print(rank, title, artist, img_url)
제일 최대로 공통되는 태그를 찾아 한번 걸러주고, 다음에 필요한 태그들을 최소한으로 선택해준다.(난 이 작업이 제일 어렵다고 느꼈다.)