텍스트 중앙정렬 : text-align :
이미지 불러오기 : background-image : url("이미지 url")
이미지 조정하기 : background-size : cover / background-position : center
padding : 안쪽으로 px을 준다
margin : 바깥쪽으로 px을 준다
로그인 페이지를 가운데로 옮기고 싶다면?
-> 일단은 div로 묶은 다음에,
background-color : green을 줘서 어느정도 대강 감을 잡고
width:300px를 준다음, margin : auto; 를 준다면 가운데 정렬이 된다.
만약 버튼을 가운데로 옮기고 싶다면?
width:100px;
margin:auto;
display:block;
display : block으로 속성을 바꾼다.
-> column 대신 row로 바꾸게 되면 나란히 배치가됨
hover를 사용해보자
-> .mytitle > button:hover{
border: 2px solid white;
color: yellow;
} -> 마우스를 위로 올리면 해당 속성대로 변함
이미지를 넣어보고 어둡게해보자
-> background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://movie-phinf.pstatic.net/20210715_95/1626338192428gTnJl_JPEG/movie_image.jpg");
class는 중첩이 가능하다
-> <button class="btn my-color">
이런 .btn과 .my-color가중첩이 가능하다.
폰트를 넣어보도록 하자
https://fonts.google.com/?subset=korean 를 검색해서 마음에드는 폰트 클럭
+select this style 을 누르고 <link href~> 를 복사하고
<title></title>
밑에 복사
그리고 <style> * { font-family: 'Black Han Sans', sans-serif}
를 넣어주면 끝
핸드폰 사이즈로 맞추기
-> .wrap{
max-width:1200px;
width:95%;
}
.mypost{
max-width:500px;
width:95%
}
max-width와 %를 사용하면 됨
CSS 불러오기
-> <link rel="stylesheet href="mystyle.css'>
부트스트랩
시작 템플릿을 복사해서 사용하면 됨
다음 https://getbootstrap.com/docs/4.0/components/buttons/ 여기 들어가서 복붙 후 사용하면됨
card 부트스트랩을 가운데로 정렬하고 싶다면?
-> div로 묶은다음, width:900px정도 주고, margin:auto; 주면 끝
<script> function hey(){alert('안녕')</script>
<button>버튼</button>
-> 변수, 자료형, 함수, 조건문, 반복문만 알면 됨
변수
->
let a = 2
let b = 3
a+b =? 5
let first_name = 'bumkyu'
let last_name = 'park'
first_name + last_name = 'bumkyupark'
자료 담는 법을 알아보자(1)
->
let a_list =['수박', '참외', '배']
a_list[0] = 수박
a_list[1]= 참외
추가하는법
a_list.push('포도')
let b_list =['철수','영희']
a_list.push(b_list) -> b_list(철수,영희)추가가 가능함
-> 고로 a_list[4][0] = '철수' 라는 값이 나옴
자료 담는 법을 알아보자(2)
-> let a_dict = {'name':'bob,'age':27}
a_dict['name'] = 'bob'
기본함수들
let a = 100
나머지 구하기
a&8 = 4
a&3 = 1
- 이메일 나누기
let myemail = sparta@gmail.com
myemail.split('@') = "sparta","gmail.com"
myemail.split('@')[1] = "gmail.com"
myemail.split('@')[1].split('.') = "gmail", "com"
myemail.split('@')[1].split('.')[0] ="gmail"
함수 조건문, 반복문
함수 : 정해진 동작을 한다
function sum(num1,num2){
return num1+num2
}
let result = sum(2,3)
result = 5
여기서 num1 = 2, num2 = 3이 되고 return이 된다.
return은 끝내고 나를 변신시켜줘 라는 뜻이다.
function mysum(num1,num2){
alert('안녕')
return num1+num2
}
let result2 = mysum(2,3) = ?
-> alert이 뜨고 차례대로 result2 = 5가 나온다.
functoin mysum(num1,num2){
alert('안녕')
}
mysum(1,2)
->
function sum(a,b){
console.log('계산을하자')
return a+b
}
let result = sum(2,3)
console.log(result)
조건문
function is_adult(age){
if(age>20){
alert('성인입니다.')
}else{
alert('아닙니다.')
}}
-> console.log(is_adult(숫자입력))
let age = 24
if( age > 20 ){
console.log('성인입니다.')
} else{
console.log('청소년입니다')
}
-> 성인입니다.
let 성별 = '남성'
if( age > 20 && 성별 =='남성'){
console.log('성인 남성입니다.')
} else{
console.log('청소년입니다')
}
-> 성인남성입니다.
반복문
for (let i =0, i<10; i++)
console.log(i) }
-> 0부터 9까지 나옴
let people =['철수','영희','민수','형준','기남','동희']
people.length = 6이나옴
let a_list =['사과','배', '감', '딸기']
for (let i=0; i<a_list.length; i++){
console.log(a_list[i])
} -> i가 0부터 1개씩 커지면서 내용물을 실행시킨다.
언제까지? a_list.length의 길이까지 커진다.
반복문예시
let scores = [
{'name':'철수', 'score':90},
{'name':'영희', 'score':85},
{'name':'민수', 'score':70},
{'name':'형준', 'score':50},
{'name':'기남', 'score':68},
{'name':'동희', 'score':30},
]
scores[0] = 철수 90
scores[1]['score'] = 85
-> for (let i=0; i<scores.length; i++){
if(scores[i]['score']>70){
console.log(scores[i]['name'])
-> 철수,영희
for(let i = 0; i< scores.length; i++){
- let name = scores[i]['name']
let score = scores[i]['score']
console.log(name,score)}
-> 철수 90, 영희 85, 민수 70 등등..
for(let i = 0; i< scores.length; i++){
let name = scores[i]['name']
let score = scores[i]['score']
if(score < 70){
console.log(name,score)}
}
-> 기남 68, 형준 50 , 동희 30
for ( let i = 0; i < mise_list.length; i++){
console.log(mise_list[i]) }
for ( let i = 0; i < mise_list.length; i++){
let gu_name = mise_list[i]['MSRSTE_NM']
let gu_mise = mise_list[i]['IDEX_MVL']
console.log(gu_name,gu_mise)}
40보다 작은 미세먼지 농도를 찾는다면?
for ( let i = 0; i < mise_list.length; i++){
let gu_name = mise_list[i]['MSRSTE_NM']
let gu_mise = mise_list[i]['IDEX_MVL']
if(gu_mise< 40 ){
console.log(gu_name,gu_mise)}
for( let i = 0; i<bikes.length; i++) {
console.log(bikes[i])}
for ( let i= 0; i<bikes.length; i++) {
let name = bikes[i]['stationName']
let bike = bikes[i]['parkingBikeCnt']
console.log(name,bike)}
let count = 0; -> 몇번 눌렀는지 알려면 값을 저장하는놈이 필요함
function hey(){
count +=1; -> 카운트를 하나 증가해줘야 겠지?
if(count % 2 == 0){ -> 어떤 수를 2로 나누었을 때 나머지가 0이면 짝수란 소리임
alert('짝수입니다.')
}else{
alert('홀수입니다.')
}
}
***
jquery를 먼저 사용하려면
-> 1.import를 해야한다
-> 2. google cdn을 복사해서 title 밑에 복붙해야한다.
input id에 id="article-url"을 기입 후, jquery를 이용해서 입력을 해보자
jquery를 이용해서 찾을 때는 -> ('#article-url').val() 을 입력하면 검색어에 어떤 것을 입력했는 지 알 수 잇음('#article-url').val('장영실')을 입력하면 검색어에 장영실로 변경이됨
CSS로 지칭이 가능함
$('#post-box').show()
$('#post-box').hide()
$('#post-box').css('width')
$('#post-box').css('width','700px') <- width 수정
$('#post-box').css('display')
를 만든다
-> 그리고 원래 기본으로 안뜨게 하려면 .posting-box에서 display:none을 주면 됨
<script>
function open_box(){
$('#post-box').show()
}
function close_box(){
$('#post-box').hide()
}
</script>
1. let txt = $('#input-q2).val() -> 우선 입력어를 txt로 설정
2. if(txt.includes('@') == true) -> includes 함수를 이용해서 @이 포함됬는지 여부를 파악.
3. alert(txt.split('@')[1].split('.')[0] -> split 함수를 이용해서, @ 기점으로 나누고 추가로 '.' 기점으로 다시 나눈다.
let txt = $('#input-q3').val()
let temp_html = `<li>${txt}</li>` -> 추가/불러오기 할 때는 백틱과 $를 쓴다.
$('#names-q3').append(temp_html) -> append 함수를 통해서 글 추가하기
-> 번외로 다 지우기 버튼 만들기$.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
-> API주소
data: {},
success: function(response){
console.log(response)
}
})
-> response에 모든 값이 들어옴 $.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {},
success: function(response){
console.log(response['RealtimeCityAir']['row'][0]) -> 조금 더 자세하게 볼 수 있음
}
})
$.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {},
success: function(response){
let rows = response['RealtimeCityAir']['row']
for(let i=0; i < rows.length; i++){
let gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
if(gu_mise<70){
console.log(gu_name,gu_mise)
}}
}
})
function q1() {
$.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {},
success: function(response){
let rows = response['RealtimeCityAir']['row'] -> 우선 rows를 ajax를 이용하여 지칭
for (let i=0; rows.length > i; i++){ -> 반복문
let gu_name = rows[i]['MSRSTE_NM'] -> gu_name을 지칭
let gu_mise = rows[i]['IDEX_MVL'] -> gu_mise를 지칭
console.log(gu_name,gu_mise)
}
}
})
}
function q1() {
$('#names-q1').empty() -> 반복안되게 지워버리기
$.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {},
success: function(response){
let rows = response['RealtimeCityAir']['row']
for (let i=0; rows.length > i; i++){
let gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
let temp_html =`<li>${gu_name} : ${gu_mise}</li>` -> temp_html을 통해 백틱으로 temp_html 설정
$('#names-q1').append(temp_html) -> 추가하기
}
}
})
}
function q1() {
$('#names-q1').empty()
$.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {},
success: function(response){
let rows = response['RealtimeCityAir']['row']
for (let i=0; rows.length > i; i++){
let gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
let temp_html = `` -> 우선 백틱으로 지정(일단 빈 문자열을 만들어야함)
if(gu_mise > 70){
temp_html =`<li class="bad">${gu_name} : ${gu_mise}</li>`
} else{
temp_html =`<li>${gu_name} : ${gu_mise}</li>`
}
$('#names-q1').append(temp_html)
}
}
})
}
<script>
function q1() {
$('#names-q1').empty()
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulbike",
data: {},
success: function(response){
let rows = response['getStationList']['row']
for(let i=0; i < rows.length; i++){
let name = rows[i]['stationName']
let rack = rows[i]['rackTotCnt']
let bike = rows[i]['parkingBikeTotCnt']
let temp_html =``
if(bike < 5){
temp_html=`<tr class="red">
<td>${name}</td>
<td>${rack}</td>
<td>${bike}</td>
</tr>`
}else{
temp_html=`<tr>
<td>${name}</td>
<td>${rack}</td>
<td>${bike}</td>
</tr>`
}
$('#names-q1').append(temp_html)
}
}
})
}
</script>
<script>
function q1() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rtan",
data: {},
success: function(response){
let url = response['url']
let msg = response['msg']
$('#img-rtan').attr('src', url) -> 'src'를 -> url로 바꾸는 코드
$('#text-rtan').text(msg) -> text 바꾸는 코드
}
})
}
</script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
success: function(response){
let temp = response['temp']
let city = response['city']
$('#temp').text(temp)
$('#city').text(city)
}
})
});
</script>
</head>
<body>
<div class="mypic">
<h1>10센치 팬명록</h1>
<p>현재기온 <span id="temp">36</span>도</p>
<p>현재위치 <span id="city"></span></p>
</div>
<script>
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
success: function(response){
let temp =response['temp']
let location =response['city']
$('#temp').text(temp)
$('#location').text(location)
}
})
</script>
</head>
<body>
<div class="mytitle">
<div class="text">
<h1>아이유 팬명록</h1>
<p>현재기온 : <span id="temp">00.0</span>도 / 현위치 :<span id="location"></span></p>
</div>
<script>
$(document).ready(function(){
listing();
});
function listing() {
$('#cards-box').empty()
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/web/api/movie",
data: {},
success: function(response){
let movies = response['movies']
for (let i = 0 ; i < movies.length; i++) {
let movie = movies[i]
let title = movie['title']
let desc = movie['desc']
let image = movie['image']
let comment = movie['comment']
let star = movie['star']
let star_image = '⭐'.repeat(star) -> 별점 넣는 방법
let temp_html = `<div class="col">
<div class="card h-100">
<img src="${image}"
class="card-img-top">
<div class="card-body">
<h5 class="card-title">${title}</h5>
<p class="card-text">${desc}</p>
<p>${star_image}</p> -> 별점 넣는 방법
<p class="mycomment">${comment}</p>
</div>
</div>
</div>`
$('#cards-box').append(temp_html)
}
}
})
}
function open_box(){
$('#post-box').show()
}
function close_box(){
$('#post-box').hide()
}
</script>
-> 파이썬 초기 셋팅
print('hello sparta') -> 실행
a=2, b=3 a+b(print) => 실행을 하면 5라는 값이 나옴
a_list =['사과','배','감'], print(a_list[1]) -> 감이 나옴
a_dict={
'name':'bob',
'age':27} -> print(a_dict['name']) => 'bob'
def sum(a,b):
return a + b -> 나를 얘로 변신시켜라 라는 뜻
result = sum(1,2)
print(result) -> 3이 찍힌다.
def is_adult(age):
if age > 15:
print('성인입니다.')
else:
print('청소년 입니다.')
is_adult(16) -> 성인입니다.
fruits = ['사과','배','배','감','수박','귤','딸기','사과','배','수박']
count = 0
for aaa in fruits:
if aaa =='사과':
count +=1
print(count)
people = [{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27}]
for ppp in people:
if ppp['age'] > 20: -> 20살 이상인 사람들의 name은?
print(ppp['name'])
설치해야할 것들
- requests
- bs4
- pymongo
- dnspython
requests 시연해보기
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"]
if gu_mise < 60:
print(gu_name)
-> for 아무거나적기 in rows
import requests
from bs4 import BeautifulSoup
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('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
#old_content > table > tbody > tr:nth-child(3) > td.title > div > a
#old_content > table > tbody > tr:nth-child(4) > td.title > div > a
movies = soup.select('#old_content > table > tbody > tr')
for movie in movies:
a = movie.select_one('td.title>div>a')
if a is not None:
print(a.text)
import requests
from bs4 import BeautifulSoup
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('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
#old_content > table > tbody > tr:nth-child(3) > td.title > div > a
#old_content > table > tbody > tr:nth-child(4) > td.title > div > a
movies = soup.select('#old_content > table > tbody > tr')
for movie in movies:
a = movie.select_one('td.title>div>a')
if a is not None:
title = a.text
rank = movie.select_one(' td:nth-child(1) > img')
star = movie.select_one(' td.point')
print(star.text)
오류가 난다면 certifi를 설치하고 아래와 같이 입력하자
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.wff24uo.mongodb.net/Cluster0?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
doc = {
'name':'bob',
'age':27
}
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.wff24uo.mongodb.net/Cluster0?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
doc = {
'name':'bob',
'age':27
}
db.users.insert_one(doc)
영화 평점 크롤링 한 것을, 이제 db에 올려보도록 하자
import requests from bs4 import BeautifulSoup from pymongo import MongoClient import certifi ca = certifi.where() client = MongoClient('mongodb+srv://test:sparta@cluster0.wff24uo.mongodb.net/Cluster0?retryWrites=true&w=majority', tlsCAFile=ca) db = client.dbsparta 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('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers) soup = BeautifulSoup(data.text, 'html.parser') movies = soup.select('#old_content > table > tbody > tr') for movie in movies: a = movie.select_one('td.title > div > a') if a is not None: title = a.text star = movie.select_one('td.point').text rank = movie.select_one('td:nth-child(1) > img')['alt'] doc = { 'title':title, 'rank':rank, 'star':star } db.movies.insert_one(doc)
크롤링 기본준비
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.wff24uo.mongodb.net/Cluster0?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
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('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
3강 숙제 크롤링(지니)
import requests
from bs4 import BeautifulSoup
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('https://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for tr in trs:
rank = tr.select_one('td.number').text[0:2].strip()
title = tr.select_one('td.info > a.title.ellipsis').text.strip()
artist = tr.select_one('a.artist.ellipsis').text
print(rank,title,artist)
4강 프레임워크를 설정해보자
- 설치해야될 것
-flask
Get 방식과 Post 방식을 살펴보자