Data Scientist 옌

매일 발전하는 IT문제해결사

국비지원교육 (22.01-22.07)/강의노트

22-06-13(월) 093일차 [JavaScript, Node.js, Python] 화살표 함수, express 모듈, 크롤링 실습

옌炎 2022. 6. 24. 11:16
728x90

수업내용


1교시 (09:30-10:20)

  • script_09.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Arrow Functions</title>
	<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
	<h1>Arrow Functions</h1>
	<p>Open the console</p>
	<script type="text/babel">

		// 함수
		var lordify = function (firstName, land) {

			if (!firstName) {
				throw new Error('lordify에 이름을 넘겨야 합니다.')
			}

			if (!land) {
				throw new Error('영주에게는 영직 있어야 합니다.')
			}

			return `${land}의 ${firstName}`
		}

		console.log( lordify("홍길동1", "멜버른"));

		// 화살표 함수
		var lordify_1 = (firstName_1, land_1) => {

			if (!firstName) {
				throw new Error('lordify에 이름을 넘겨야 합니다.')
			}

			if (!land) {
				throw new Error('영주에게는 영직 있어야 합니다.')
			}

			return `${land_1}의 ${firstName_1}`
		}

		console.log(lordify_1("홍길동2", "가산"));

	</script>
</body>
</html>

  • script_09_1.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Arrow Functions</title>
	<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
	<h1>Arrow Functions</h1>
	<p>Open the console</p>
	<script type="text/babel">

		// 함수
		var lordify = function (firstName, land) {

			return `${land}의 ${firstName}`
		}

		console.log( lordify("홍길동1", "멜버른"));

		// 화살표 함수
		var lordify_1 = (firstName_1, land_1) => {

			return `${land_1}의 ${firstName_1}`
		}

		console.log(lordify_1("홍길동2", "가산"));

	</script>
</body>
</html>

2교시 (10:30-11:20)

  • script_10.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Arrow Functions</title>
	<script src="http://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
	<h1>Arrow Functions</h1>
	<p>Open the console</p>
	<script type="text/babel">

		var gangwon = {

			resorts:
			["Kirkwood", "Squaw", "Alpine", "Heavenly", "Northstart"],
			print: function(delay=1000) {

				setTimeout(function() {

					console.log(gangwon.resorts.join(','))
				}, delay)
			}
		}

		gangwon.print()
		
	</script>
</body>
</html>

  • script_11.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Arrow Functions</title>
	<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js">
	</script>
</head>
<body>
	<h1>Arrow Functions</h1>
	<p>Open the console</p>
	<script type="text/babel">

		// 함수와 bind를 사용함
		
		var tahoe = {

			resorts: ["용평", "평창", "강촌", "강릉", "홍천"],
			print: function(delay=1000) {

				setTimeout(function() {
					console.log(tahoe.resorts.join(","))
				}.bind(tahoe), delay)
			}
		}

		/* 오류
		var tahoe = {

			resorts: ["용평", "평창", "강촌", "강릉", "홍천"],
			print: function(delay=1000) {

				setTimeout(function() {
					console.log(this.resorts.join(","))
				}.bind(this), delay)
			}
		}
		*/

		tahoe.print()

	</script>
</body>
</html>

  • script_12.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Arrow Functions</title>
	<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js">
	</script>
</head>
<body>
	<h1>Arrow Functions</h1>
	<p>Open the console</p>
	<script type="text/babel">

		// 화살표 함수를 너무 많이 사용함. this가 window를 가리킴

		var gangwon = {

			resorts: ["용평", "평창", "강촌", "강릉", "홍천"],
			print: (delay=1000) => {

                      setTimeout(() => {
                        console.log(gangwon.resorts.join(","))
                      }, delay)
                    }
                  }     
		/* 오류
		var gangwon = {

			resorts: ["용평", "평창", "강촌", "강릉", "홍천"],
			print: (delay=1000) => {

                      setTimeout(() => {
                        console.log(this.resorts.join(","))
                      }, delay)
                    }
                  }
        */
		gangwon.print()

	</script>
</body>
</html>

3교시 (11:30-12:20)

  • client → http(모듈) → express(모듈)
  • client → react → express
  • espress_04.js
// app5.js

var express = require('express')
    , http = require('http');

var app = express();

app.use(function(req, res, next) {
    console.log('첫 번째 미들웨어에서 요청을 처리함.');
    
    res.redirect('http://google.co.kr');
    // next();
});

// use() 메소드로 미들웨어 등록
app.use('/', function(req, res, next) {
    console.log('두 번째 미들웨어에서 요청을 처리함.')
    
    res.writeHead('200', {'Content-Type': 'text/html;charset=utf8'});
    res.end('<h1>Express 서버에서 ' + req.user + '가 응답한 결과입니다.</h1>')
});

http.createServer(app).listen(3000, function() {
    console.log('Express 서버가 3000번 포트에서 시작됨.')
});

4교시 (12:30-13:20)

  • express_05.js
var express = require('express')
	, http = require('http');

var app = express();

app.use(function(req, res, next) {
	console.log('첫 번째 미들웨어에서 요청을 처리함');

	var userAgent = req.header('User-Agent');
	var paramName = req.query.name;

	res.writeHead('200', {'Content-Type': 'text/html;charset=utf8'});
	res.write('<h1>Express 서버에서 응답한 결과입니다</h1>');
	res.write('<div><p>User-Agent : ' + userAgent + '</p></div>');
	res.write('<div><p>paramName : ' + paramName + '</p></div>');
	res.end();
});

http.createServer(app).listen(3000, function(){
	console.log('Express 서버가 3000번 포트에서 시작됨');
});

  • login.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>로그인 테스트</title>
</head>
<body>
	<h3>로그인</h3>
	<hr>
	<form method="POST">
		<table>
			<tr>
				<td><label>아이디</label></td>
				<td><input type="text" name="id"></td>
			</tr>
			<tr>
				<td><label>비밀번호</label></td>
				<td><input type="text" name="password"></td>
			</tr>
		</table>
		<input type="submit" value="전송" name="">
	</form>
</body>
</html>
  • express_06.js
/*

npm install path --save 
npm install body-parser --save
npm install serve-static --save 

03_express/public/login.html


node express_06.js

localhost:3000/public/login.html

*/

// Express 기본 모듈 불러오기
var express = require('express')
	, http = require('http')
	, path = require('path');

// Express의 미들웨어 불러오기
var bodyParser = require('body-parser')
	, static = require('serve-static');

// Express 객체 설정
var app = express();

// 기본 속성 설정
app.set('port', process.env.PORT || 3000);

// body-parser 미들웨어를 사용해 application/x-www-form-urlencoded 파싱
app.use(bodyParser.urlencoded({extended: false}));

// body-parser 미들웨어를 사용해 application/json 파싱
app.use('/public', static(path.join(__dirname, 'public')));

// 미들웨어 파라미터 확인
app.use(function(req, res, next) {
	console.log('첫 번째 미들웨어에서 요청을 처리함');

	// POST 방식 : req.body.id
	// GET 방식 : req.query.id
	// POST/GET 방식 : req.body.id || req.query.id
	var paramId = req.body.id || req.query.id;
	var paramPassword = req.body.password || req.query.password;

	res.writeHead('200', {'Content-Type': 'text/html;charset=utf8'});
	res.write('<h1>Express 서버에서 응답한 결과입니다.</h1>');
	res.write('<div><p>Param id : ' + paramId + '</p></div>');
	res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
	res.end();
});

http.createServer(app).listen(3000, function() {
	console.log('Express 서버가 3000번 포트에서 시작됨');
});


5교시 (14:30-15:20)

  • login2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>로그인 테스트</title>
</head>
<body>
	<h3>로그인</h3>
	<hr>
	<form method="POST" action="/process/login">
	    <table>
	        <tr>
	            <td><label>아이디</label></td>
	            <td><input type="text" name="id"></td>
	        </tr>
	        <tr>
	            <td><label>비밀번호</label></td>
	            <td><input type="text" name="password"></td>                    
	        </tr>
	    </table>
	    <input type="submit" value="전송" name="">
	</form>	
</body>
</html>
  • express_07.js
// Express 기본 모듈 불러오기
var   express = require('express')
    , http = require('http')
    , path = require('path');

// Express의 미들웨어 불러오기
var bodyParser = require('body-parser')
    , static = require('serve-static');

// 익스프레스 객체 생성
var app = express();

// 기본 속성 설정
app.set('port', process.env.PORT || 3000);

// body-parser 미들웨어를 사용해 application/x-www-form-urlencoded 파싱
app.use(bodyParser.urlencoded({extended: false}));

// body-parser 미들웨어를 사용해 application/json 파싱
app.use(bodyParser.json());

// static 미들웨어 serve-static 를 사용해 패스 매핑
// app.use('/public', static(path.join(__dirname, 'public')));
app.use('/public', static(path.join(__dirname, 'public')));

// 라우터 객체 참조
var router = express.Router();

// 미들웨어 파라미터 확인
// 라우팅 함수 등록
router.route('/process/login').post(function(req, res) {
    console.log('/process/login 처리함');
    
    /*
        POST 방식 : req.body.id
        GET 방식 : req.query.id
        POST/GET 방식 : req.body.id || req.query.id
    */
    var paramId = req.body.id || req.query.id;
    var paramPassword = req.body.password || req.query.password;
    
    res.writeHead('200', {'Content-Type': 'text/html;charset=utf8'});
    res.write('<h1>Express 서버에서 응답한 결과입니다.</h1>');
    res.write('<div><p>Param id : ' + paramId + '</p></div>');
    res.write('<div><p>Param password : ' + paramPassword + '</p></div>');
    res.write("<br><br><a href='/public/login2.html'>로그인 페이지로 돌아기기</a>");    
    res.end();
});

// 라우터 객체를 app 객체에 등록
app.use('/', router);

http.createServer(app).listen(3000, function() {
    console.log('Express 서버가 3000번 포트에서 시작됨.')
});

6교시 (15:30-16:20)

  • beautifulsoup_05.py
from bs4 import BeautifulSoup

html = """
        <html>
        <body>
        <div id="meigen">
        <h1>위키북스 도서</h1>
        <ul class="items">
            <li>유니트 게임 이펙트 입문</li>
            <li>스위프트로 시작하는 아이폰 앱 개발 교과서</li>
            <li>모던 웹사이트 디자인 정석</li>
        </ul>
        </div>
        </body>
        </html>
       """

# soup.select_one(선택자) : CSS 선택자로 요소 하나를 추출
# soup.select(선택자) : CSS 선택자로 요소 여러개를 리스트로 추출

soup = BeautifulSoup(html, 'html.parser')

h1 = soup.select_one("div#meigen > h1").string
print("h1 >>> : ", h1)
li_lit = soup.select("div#meigen > ul.items > li")
for li in li_lit:
    print("li >>> : ", li.string)

  • beautifulsoup_06.py
from bs4 import BeautifulSoup
import urllib.request as req

# url = "http://info.finance.naver.com/marketindex"
url = "https://finance.naver.com/marketindex/"
res = req.urlopen(url)

soup = BeautifulSoup(res, "html.parser")
print(soup)

price = soup.select_one("div.head_info > span.value").string
print("usd/krw = ", price)

  • beautifulsoup_07.py
from bs4 import BeautifulSoup
import urllib.request as req
import datetime

url = "https://finance.naver.com/marketindex/"
res = req.urlopen(url)

soup = BeautifulSoup(res, "html.parser")
# print(soup)

price = soup.select_one("div.head_info > span.value").string
print("usd/krw = ", price)

t = datetime.date.today()
frame = "./data/" + t.strftime("%Y-%m-%d") + ".txt"

with open(frame, "w", encoding="utf-8") as f:
    f.write(price)


"""
url = "https://finance.naver.com/marketindex/"
res = req.urlopen(url)

soup = BeautifulSoup(res, "html.parser")

# 휘발유, 국제금, 국내금 가격 찾기
oil = soup.select_one("a.head.gasoline > div > span.value").string
int_gold = soup.select_one("a.head.gold_inter > div > span.value").string
dom_gold = soup.select_one("a.head.gold_domestic > div > span.value").string

print("oil >>> : ", oil)
print("int_gold >>> : ", int_gold)
print("dom_gold >>> : ", dom_gold)
"""

7교시 (16:30-17:20)

  • 위의 데이터 가져오기 연습

8교시 (17:30-18:30)

  • 스프링 코드 버전업하기

Notes

  • 카트에 넣기, 글쓰기, 댓글 쓰기, 좋아요는 세션을 고려해서 하기
  • 상품 등록은 관리자만 가능(관리자 추가 로직)
  • login 없을 때: SNS login
  • 다음 주 화요일까지 해보기

728x90