Data Scientist 옌

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

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

22-06-10(금) 092일차 [JavaScript, Node.js, Python] 호이스팅, express, 크롤링

옌炎 2022. 6. 24. 10:42
728x90

수업내용


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

  • 프로젝트 이야기

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

  • [36p 하단, 31p] 호이스팅 : 끌어올리다
  • script_06.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Document</title>
	<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
	<h3>ES6 FUNCTION</h3>
	<hr>
	<script type="text/babel">

		function logFun() {
			console.log("로그를 잘 찍자 !!!");
		}

		function logFun_1() {
			console.log("함수를 호출 :: 로그를 잘 찍자 !!!");
		}
		logFun_1();

		hello();
		// 함수 선언
		function hello() {
			alert("hey!!!");
		}

		// ES6 함수
		function logActivity(name="홍길동", activity="운동을 좋아한다") {
			console.log(`${name}은 ${activity}. `);
		}

		logActivity()
		
		hey();
		// 표현식 함수 선언
		const hey = function(){
			alert("hey!!!");
		}

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

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

		var defaultPerson = {
			name : {
				first: "길동",
				last: "홍"
			},
			favActivity: "헬스"
		}

		function logActivity(p=defaultPerson) {
			console.log(`${p.name.first}은 ${p.favActivity}를 좋아합니다.`);
		}

		logActivity()
	</script>
</body>
</html>

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

  • script_08.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
	<title>Documemt</title>
</head>
<body>
	<h3>화살표 함수 : Arrow Funvtion</h3>
	<hr>
	<script type="text/babel">
		
		// 일반 힘수
		// function : 키워드
		// 사용자 정의 함수 이름
		// () : 소괄호 : 파라미터 받는, 선언하는 공간
		// {} : 함수 블록
		// return : 키워드

		var lordify = function (firstname) {

			return `켄터베리의 ${firstname}`
		}

		console.log( lordify("홍길동"))
		console.log( lordify("홍길동"))

		// Arrow function
		var lordify_1 = firstname => `켄터베리의 ${firstname}`

		console.log( lordify_1("홍길동"))
		console.log( lordify_1("홍길동"))

		var lordify_2 = (firstName, land) => `${land}의 ${firstName}`

		console.log( lordify_2("홍길동", "브리즈번"))
		console.log( lordify_2("홍길동", "시드니"))
	</script>
</body>
</html>

  • Node.js

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

Node.js - express

npm install express --save
http-server -p 3000
  • express_01.js
// Express 기본 모듈 불러오기
// express 모듈은 웹 서버를 위해 만들어진 것으로 http 모듈 위에서 동작한다.
// express 모듈을 사용할 때는 항상 http 모듈도 함께 불러들인다.

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

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

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

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

// 기본 포트를 app 객체에 속성으로 설정
app.set('port', process.env.PORT || 3000);

// Express 서버 시작
http.createServer(app).listen(app.get('port'), function(){
	console.log('익스프레스 서버를 시작했습니다 : ' + app.get('port'));
});

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

var app = express();

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

	req.user = 'mike';
	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번 포트에서 시작됨');
});

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

var app = express();

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

	res.send({name: '소녀시대', age:20});
});

// 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번 포트에서 시작됨');``
});


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

  • 데이터 게더링이란

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

  • request_01.py
import requests

url = "http://www.python.org"

res = requests.get(url)
print('res >>> : ', res)

python_html = res.text
print('python_html >>> : \n', python_html)
  • request_02.py
import requests

url = "http://www.python.org"

res = requests.get(url)
print('res >>> : ', res)

python_html = res.text
print('python_html >>> : \n', python_html)

  • request_03.py
import requests

urls = ["http://www.naver.com/", "https://www.python.org/"]
filename = "robots.txt"

for url in urls:
    file_path = url + filename
    print('file_path >>> : ', file_path)
    res = requests.get(file_path)
    print(res.text)
    print('\n')

'''
User-agent: *
Disallow: /
Allow : /$ 
모든 문서에 대해 접근을 차단하고, 첫 페이지에 대해서만 허가
사용 중인 사이트: 네이버 메인화면[2], 네이트 메인화면, 줌 메인화면 등.

User-agent: *
Allow: /
모든(*) 로봇(User-agent)에게 루트 디렉토로리(/)이하의 문서에 대한 접근을 허락(Allow)한다.

User-agent: *
Disallow: /
모든(*) 로봇(User-agent)에게 루트 디렉토로리(/)이하의 문서에 대한 접근을 차단(Disallow)한다.

User-agent: *
Disallow: /temp
모든(*) 로봇(User-agent)에게 특정 디렉토로리(/temp/)이하의 문서에 대한 접근을 차단(Disallow)한다.

User-agent: googlebot
Disallow: /
특정한 로봇(googlebot)에게 모든 문선에 대한 접근을 차단(Disallow)한다.
'''

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

  • beautifulsoup_01.py
from bs4 import BeautifulSoup

'''
BeautifulSoup
: HTML, XML만 분석하는 모듈, 도구이다. 셀렉터 기술
: BeautifuleSoup을 잘 하려면 CSS Selector를 잘 해야 한다
: 파일을 다운로드 하는 기능은 없다.
: 스크레이핑 기술이다.
'''

html = """
        <html>
            <body>
                <h1>스크레이핑이란?</h1>
                <p>웹 페이지를 분석하는 것</p>
                <p>원하는 부분을 추출하는 것</p>
            </body>
        </html>
       """

soup = BeautifulSoup(html, 'html.parser')
h1 = soup.html.body.h1
p1 = soup.html.body.p
p2 = p1.next_sibling.next_sibling

print('h1 >>> : ', h1.string)
print('p1 >>> : ', p1.string)
print('p2 >>> : ', p2.string)

  • beautiful_01.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>스크레이핑이란?</h1>
	<p>웹 페이지를 분석하는 것</p>
	<p>원하는 부분을 추출하는 것</p>
</body>
</html>
  • beautifulsoup_02.py
from bs4 import BeautifulSoup
import urllib.request as req

url = "http://localhost:8088/kosmoSpring/kos_beautifulsoup/beautiful_01.html"
res = req.urlopen(url)

soup = BeautifulSoup(res, 'html.parser')
h1 = soup.html.body.h1
p1 = soup.html.body.p
p2 = p1.next_sibling.next_sibling

print('h1 >>> : ', h1.string)
print('p1 >>> : ', p1.string)
print('p2 >>> : ', p2.string)

from bs4 import BeautifulSoup

html = """
        <html>
            <body>
                <h1 id="title">스크레이핑이란?</h1>
                <p id="body"> 웹 페이지를 분석하는 것</p>
                <p>원하는 부분을 추출하는 것</p>
            </body>
        </html>
       """

soup = BeautifulSoup(html, 'html.parser')
# BeautifulSoup 에서는
# HTML의 구조와 루트 요소인 <html>에서 부터
# . : 마침표, 링크 연산자를 사용하여 값에 접근할 수 있다.
# soup.html.body.h1

print("soup.prettify() 함수는 html 구조를 파악하기 쉽게 바꿔준다 >>> : \n", soup.prettify())
title1 = soup.html.body.h1
print("title1 >>> : ", title1)
print("type(title1) >>> : ", type(title1))
print("type(title1.attrs) >>> : ", type(title1.attr))
print('id' in title1.attrs)
print("title1['id'] >>> : ", title1['id'])

title = soup.find(id="title")
body = soup.find(id="body")

print("#title >>> : ", title.string)
print("#body >>> : ", body.string)

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

html = """
<html><body>
   <ul>
    <li><a href="http://naver.com">naver</a></li>
    <li><a href="http://daum.net">daum</a></li>
   </ul>
</body></html>
"""
soup = BeautifulSoup(html, 'html.parser')

links = soup.find_all("a")

for a in links:
    href = a.attrs['href']
    text = a.string
    print(text, ">", href)

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

url = "http://naver.com"
res = req.urlopen(url)

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

links = soup.find_all("a")

for a in links:
    href = a.attrs['href']
    text = a.string
    print(text, ">", href)

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

  • 스프링 코드 버전업하기

Notes


728x90