728x90
반응형

1주차에는 HTML , CSS , Javascript
2주차에 JQuery, Ajax

3주차 파이썬, MonggoDB

 

지금까지 프론트앤드 눈 앞에 보이는 것만 배웠었는데

드디어 백앤드 서버단을 시작했다.

 

내일배움캠프 시작전에도 프론트앤드

눈앞에 보이는 것을 만드는 작업만 했는데,

화면에 안보이지만 뒤에서 데이터를 정리해보니

이것도 나름의 재미가 있는 것 같다.

 

3주차 개인적인 후기

 

3주차만에 여러가지 언어를 배우다보니

다 배울 수 있을까 걱정이 많았다.

 

그러나 생각보다 비슷한 문법이기에

이해하는데 어렵지는 않았다.

 

다만 비슷하면서 다른 문법이기에

계속 반복하여 코드를 작성하여 익숙해지는 방법밖에는 없을 것 같다.

 

728x90
반응형
728x90
반응형

 

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')



musics = soup.select('#body-content > div.newest-list > div > table > tbody > tr')

#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.number
#body-content > div.newest-list > div > table > tbody > tr:nth-child(2) > td.number

#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.title.ellipsis
#body-content > div.newest-list > div > table > tbody > tr:nth-child(2) > td.info > a.title.ellipsis

#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis
#body-content > div.newest-list > div > table > tbody > tr:nth-child(2) > td.info > a.artist.ellipsis

for music in musics:
        title = music.select_one('td.info > a.title.ellipsis').text.strip()
        rank = music.select_one('td.number').text[0:2].strip()
        artist = music.select_one('td.info > a.artist.ellipsis').text.strip()
        print(rank, title, artist)
728x90
반응형
728x90
반응형

기초 코드

from pymongo import MongoClient
client = MongoClient('mongodb+srv://text:sparta@cluster0.tvnfddc.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

 

# 저장 - 예시
doc = {'name':'bobby','age':21}
db.users.insert_one(doc)

# 한 개 찾기 - 예시
user = db.users.find_one({'name':'bobby'})

# 여러개 찾기 - 예시 ( _id 값은 제외하고 출력)
all_users = list(db.users.find({},{'_id':False}))

# 바꾸기 - 예시
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})

# 지우기 - 예시
db.users.delete_one({'name':'bobby'})

 

첫단계 데이터 쌓기

from pymongo import MongoClient
client = MongoClient('mongodb+srv://text:sparta@cluster0.tvnfddc.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

doc = {
    'name' : 'bob',
    'age' : 27
}

db.users.insert_one(doc)

유저 리스트 부르기

from pymongo import MongoClient
client = MongoClient('mongodb+srv://text:sparta@cluster0.tvnfddc.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

all_users = list(db.users.find({},{'_id':False}))

for user in all_users:
    print(user)
728x90
반응형
728x90
반응형

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)

Requests + bs4 조합 기본코드

 

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')

print (soup)

크롤링 예제1

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(2) > td.title > div > a

movies = soup.select('#old_content > table > tbody > tr')

for moive in movies:
    a = moive.select_one('td.title > div > a')
    if a is not None:
        print(a.text)

크롤링 예제2

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(2) > td.title > div > a

#old_content > table > tbody > tr:nth-child(2) > td:nth-child(1) > img
#old_content > table > tbody > tr:nth-child(3) > td:nth-child(1) > img

#old_content > table > tbody > tr:nth-child(2) > td.point
#old_content > table > tbody > tr:nth-child(9) > td.point

movies = soup.select('#old_content > table > tbody > tr')

for moive in movies:
    a = moive.select_one('td.title > div > a')

    if a is not None:
        title = a.text
        rank = moive.select_one('td:nth-child(1) > img')['alt']
        star = moive.select_one('td.point').text
        print(rank, title, star)
728x90
반응형

'코딩공부 > 파이썬' 카테고리의 다른 글

[3] 팬사이트(팬명록) 만들기 퀴즈  (0) 2022.10.26
[2] 영화 감상평 사이트  (0) 2022.10.26
[1] 화성땅 공동구매 프로젝트  (0) 2022.10.26
monggoDB 기초  (0) 2022.10.23
파이썬 함수  (0) 2022.10.23
728x90
반응형

함수

def sum(a,b) :
    print('더하자!')
    return a+b

result = sum(1,2)
print(result)

조건문

def is_adult(age):
    if age > 20:
        print('성인입니다')
    else:
        print('청소년입니다')

is_adult(15)

반복문 (리스트예제)

fruits = ['사과','배','배','감','수박','귤','딸기','사과','배','수박']

count = 0
for fruit in fruits:
    if fruit == '사과':
        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 person in people:
    if person['age'] > 20:
        print(person['name'])
728x90
반응형
728x90
반응형
<script>
    function q1() {
                $('#names-q1').empty();
        $.ajax({
            type: "GET",
            url: "http://spartacodingclub.shop/sparta_api/seoulair",
            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'];

                    let temp_html = ``

                    if ( gu_mise > 30){
                        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>
<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="urgent">
                                        <td>${name}</td>
                                        <td>${rack}</td>
                                        <td>${bike}</td>
                                    </tr>`
                        } else {
                        temp_html = `<tr class>
                                        <td>${name}</td>
                                        <td>${rack}</td>
                                        <td>${bike}</td>
                                    </tr>`
                    }

                    $('#names-q1').append(temp_html)
                }

            }
        })
    }
</script>
<script>
    $.ajax({
        type: "GET",
        url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
        data: {},
        success: function (response) {
            let temp = response['temp']
            $('#temp').text(temp);
        }
    })
</script>
728x90
반응형

'기초코드' 카테고리의 다른 글

Git Bash 작동코드  (0) 2022.10.27
OG태그  (0) 2022.10.27
★기본 CSS노말라이즈★  (0) 2022.10.21
인라인 그리드, 이미지 박스  (0) 2022.10.21
메뉴박스 노말라이즈  (0) 2022.10.20
728x90
반응형
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>

    <title>★숙제2★</title>

    <link href="https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Gowun Dodum', sans-serif;
        }


        .mytitle {
            height: 300px;


            background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://mblogthumb-phinf.pstatic.net/MjAyMTEyMzBfMjU3/MDAxNjQwODIzNTM5ODU4.4N5iYjgtyzTpiKCe5RlPuNM5aRqP-rxu8Lv4M7PIYy8g.FYFlO1cup4cXoyBEgOtSEWpw_baR76D5h_JwiJdCQyIg.JPEG.letis_make_idea/asdasd.jpg?type=w800");
            background-position: center 20%; /*높이 맞추기*/
            background-size: cover;

            color: white;

            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }

        .mybtn {
            display: flex;
            flex-direction: row;
            justify-content: left;
            align-items: center;
            margin-top: 10px;
        }

        .mypost {
            max-width: 500px;
            width: 95%;

            margin: 20px auto 0px auto;
            box-shadow: 0px 0px 3px 0px gray;
            padding: 20px;
        }

        blockquote {
            margin: 5px;
            padding: 5px
        }

        .card {
            margin: 10px 0px 10px 0px;
        }
        .form-floating{
            margin-top:10px;
        }
    </style>
    <script>
        $(document).ready(function () {
            alert('다 로딩됐다!')
        });

        $.ajax({
            type: "GET",
            url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
            data: {},
            success: function (response) {
                let temp = response['temp']
                let temp_html = `<p>${'temp'}</p>`

                $('#temp').text(temp)
            }
        })

    </script>

</head>

<body>
<div class="mytitle">
    <h1>🎻릴러말즈 팬사이트🎻</h1>
    <p>현재기온 : <span id="temp">00.0</span>도</p>
</div>
<div class="mypost">
    <div class="form-floating mb-3">
        <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
        <label for="floatingInput">닉네임</label>


        <div class="form-floating">
                <textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea2"
                          style="height: 100px"></textarea>
            <label for="floatingTextarea2">응원댓글</label>
        </div>
        <div class="mybtn">
            <button type="button" class="btn btn-dark">응원남기기</button>
        </div>
    </div>
    <div class="card">
        <div class="card-body-1">
            <blockquote class="blockquote mb-0">
                <p>TRIP 노래 너무 좋아요~!</p>
                <footer class="blockquote-footer">힙합맨 <cite title="Source Title"></cite>
                </footer>
            </blockquote>
        </div>
    </div>
    <div class="card">
        <div class="card-body-1">
            <blockquote class="blockquote mb-1">
                <p>성산히어로 뮤비 내주세요>_<</p>
                <footer class="blockquote-footer">성산주민1 <cite title="Source Title"></cite>
                </footer>
            </blockquote>
        </div>
    </div>
    <div class="card">
        <div class="card-body-1">
            <blockquote class="blockquote mb-1">
                <p>야망으로 채워줘요~릴러말즈💘</p>
                <footer class="blockquote-footer">엠비션보이 <cite title="Source Title"></cite>
                </footer>
            </blockquote>
        </div>
    </div>


</div>
</body>


</html>
728x90
반응형
728x90
반응형

<노말라이즈 기본> - 습관화 할 것

 

* {
  margin:0;
}

html, body{
  height:100%;
  width:100%;
}

 

/* HMTL 부분 기본설정 */

<section class="section-1 con-min-width">

    <div class="con">

        <div class="img-box"></div>

    </div>

</section>

 

/* CSS 기본설정 */

/* 폰트 시작 */
@font-face {
  font-family: 'LotteMartDream';
  font-style: normal;
  font-weight: 400;
  src: url('//cdn.jsdelivr.net/korean-webfonts/1/corps/lottemart/LotteMartDream/LotteMartDreamMedium.woff2') format('woff2'), url('//cdn.jsdelivr.net/korean-webfonts/1/corps/lottemart/LotteMartDream/LotteMartDreamMedium.woff') format('woff');
}

@font-face {
  font-family: 'LotteMartDream';
  font-style: normal;
  font-weight: 700;
  src: url('//cdn.jsdelivr.net/korean-webfonts/1/corps/lottemart/LotteMartDream/LotteMartDreamBold.woff2') format('woff2'), url('//cdn.jsdelivr.net/korean-webfonts/1/corps/lottemart/LotteMartDream/LotteMartDreamBold.woff') format('woff');
}

@font-face {
  font-family: 'LotteMartDream';
  font-style: normal;
  font-weight: 300;
  src: url('//cdn.jsdelivr.net/korean-webfonts/1/corps/lottemart/LotteMartDream/LotteMartDreamLight.woff2') format('woff2'), url('//cdn.jsdelivr.net/korean-webfonts/1/corps/lottemart/LotteMartDream/LotteMartDreamLight.woff') format('woff');
}

html {
  font-family: 'LotteMartDream', sans-serif;
}
/* 폰트 끝 */

/* 노말라이즈 시작 */
body, ul, li {
  margin:0;
  padding:0;
  list-style:none;
}

a {
  color:inherit;
  text-decoration:none;
}
/* 노말라이즈 끝 */

/* 라이브러리 시작 */
.con {
  margin-left:auto;
  margin-right:auto;
}

.block {
  display:block;
}

.img-box > img {
  width:100%;
  display:block;
}

.bg-red {
  background-color:red;
}

.bg-blue {
  background-color:blue;
}

.inline-grid {
  font-size:0;
}

.inline-grid > * {
  font-size:1rem;
  display:inline-block;
  vertical-align:top;
}

.width-10p {
  width:10%;
}
/* 라이브러리 끝 */

/* 커스텀 시작 */
:root {
  --site-width:1200px;
}

.con-min-width {
  min-width:var(--site-width);
  padding:0 10px;
}

.con {
  width:var(--site-width);
}

/* 이미지 리스트 박스 시작 */
/* 이미지 리스트 박스 끝 */

/* 커스텀 끝 */

728x90
반응형

'기초코드' 카테고리의 다른 글

OG태그  (0) 2022.10.27
Ajax 기본골격  (0) 2022.10.21
인라인 그리드, 이미지 박스  (0) 2022.10.21
메뉴박스 노말라이즈  (0) 2022.10.20
주석표  (0) 2022.10.19

+ Recent posts