Programming/Python 웹 스크래퍼 만들기

Python Flask Render Template

2022. 12. 28. 21:00

6.2 Render Template 

 

이전 게시물에서 했던 Flask 로 웹 페이지를 만들었던 것을 연습해본다.

그리고 사용자에게 HTML 을 전달하는 방법을 찾아본다.

HTML Template 을 작성한 후 사용자에게 나의 data를 넣어서 전달하면 더 좋을거 같다.

 

from flask import Flask

app = Flask("JobScrapper")

@app.route("/")
def home():
    return 'Welcome our website'

@app.route("/hello")
def hello():
    return 'hello you!'

app.run("0.0.0.0")

콘솔창:

새로운 크롬창을 열어서 주소창에 127.0.0.1:5000/hello 를 입력해서 들어간다.

@app.route("/") →  주소창에 " / " 입력시 아래 정의된 함수가 return 하는 페이지로 연결된다.

( return 'Welcome our website' )

 

@app.route("/hello") →  주소창에 " /hello " 입력시 아래 정의된 함수가 return 하는 페이지로 연결된다.

( return 'hello you!' )

 

주의 할 점은 기존에 코드가 실행되어 있으면 CTRL + C 를 눌러서 멈춘 후 다시 실행해야 작동된다는 것이다.

 

 

이제 HTML 을 return 해본다. 사용자에게 HTML 을 전달해주는것이다.

<h1>태그를 붙여서 코드를 작성해본다.

from flask import Flask

app = Flask("JobScrapper")

@app.route("/")
def home():
    return '<h1>Welcome to our website</h1>'

@app.route("/hello")
def hello():
    return 'hello you!'

app.run("0.0.0.0")

코드 실행 후 크롬창 열고 주소창에 127.0.0.1:5000 입력해서 들어가면 HTML 이 나온다.

이번에는 a href 태그를 넣어 링크를 만들어본다.


a href 태그 속성을 먼저 알아본다.

href 속성은 <a> 태그(Tag)를 통해 연결할 주소를 지정 한다.

기본 사용법은 아래와 같다.

<a href="http://naver.com">네이버로 이동하기</a>


from flask import Flask

app = Flask("JobScrapper")

@app.route("/")
def home():
    return '<h1>Welcome to our website</h1><a href=/hello>go to hello</a>'

@app.route("/hello")
def hello():
    return 'hello you!'

app.run("0.0.0.0")

다시 코드를 멈췄다 코드 재실행 후 크롬창 열고 주소창에 127.0.0.1:5000 입력해서 들어가면 아래와 같이 출력된다.

go to hello 를 클릭하면 hello 페이지로 들어간다.

많은 HTML 을 보내고 싶은 경우 위와 같은 방법은 한계가 있다.

vs code 에서 새로운 폴더를 만들고 templates 라고 이름을 짓는다.

Flask 가 templates 라는 이름의 폴더를 찾아보기 때문에 소문자 그대로 폴더이름을 짓는다.

또한 폴더 위치도 main.py 와 같은 선상에 있어야한다. ( 다른 폴더 안에 있거나 하면 안된다. )

templates 폴더 안에 home.html 이라는 새로운 파일을 만든다.

chromedriver.exe 는 이전에 indeed 스크래핑을 위한 프로그램이다. ( 상관 X )

 

이제 home.html 에서 ! 입력 후 tab 을 누르면 html 예제 코드가 작성된다.

 

아래처럼 자동으로 작성된다. ( home.html )

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

나한테 필요한 코드로 변경 ( home.html 에서 작성)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Job Scrapper</title>
</head>
<body>
    <h1>Hello to you!</h1>
</body>
</html>

다시 main.py 로 돌아와서, 문자열을 return 하는 대신 render_template을 import 한다.

home 함수에서 기존의 텍스트 ( <h1>Welcome to our website</h1><a href=/hello>go to hello</a> ) 를

return 하는 대신에 render_template이라는 함수를 호출하고, Flask 에게 home.html 파일을 render 해달라고 한다.

( templates 폴더의 home.html 과 reder_template 안의 파일명이 동일 해야한다. )

 

< main.py >

from flask import Flask, render_template

app = Flask("JobScrapper")

@app.route("/")
def home():
    return render_template("home.html")

@app.route("/hello")
def hello():
    return 'hello you!'

app.run("0.0.0.0")

새로운 크롬창을 열어서 주소창에 127.0.0.1:5000 입력 후 들어가면

아까 home.html 에서 입력한 아래 title 과 body 가 웹 페이지에 그대로 출력된다.

( 만약 백지 상태의 웹 페이지가 출력되면 home.html 을 저장 후 다시 실행해본다. )

 

 

이번에는 HTML 에 변수를 넣는 작업 ( main.py 에서 작성 → home.html 로 보내주는 작업을 해본다. )

HTML 에 변수를 넣는 원리는, Flask 에서 변수를 replace 하여 HTML로 보여준다. 

main.py 에서 name 변수를 작성하고 →  home.html 에 name 이라는 변수를 보낸다.

 

< main.py > - name="james" 추가

from flask import Flask, render_template

app = Flask("JobScrapper")

@app.route("/")
def home():
    return render_template("home.html", name="james")

@app.route("/hello")
def hello():
    return 'hello you!'

app.run("0.0.0.0")

 

< home.html > - {{name}} 추가 →  {{ }} 중괄호 2개 적고 안에 변수 이름(name) 넣는다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Job Scrapper</title>
</head>
<body>
    <h1>Hello to you! My name is {{name}}</h1>
</body>
</html>

크롬창을 새로 열고 주소창에 127.0.0.1:5000 입력

 

여기서 james 는 python 에서 넘어왔다, python은 백엔드 이며, 

이 james 라는 데이터, 문자열은 백엔드에서 부터 전달되고 있다.

Flask 에서는 사용자가 홈페이지에 접근하면,

Flask 는 여기 있는 main.py의 home 함수에서 home.html 파일을 가져다가

home.html

아래 home.html 의 {{name}} 값을 james 로 바꿔준다.

당연히 사용자 눈에는 {{name}} 이라고 출력되지 않으며 name의 변수값 james 가 출력된다.

 


< Flask 사용할 때 Python 에서 변수 입력 시 html 동작 방식 >

 

사용자의 request 가 도착하면 Flask 는 변수( name="james" )를 가져다가

HTML templates 안에 있는 변수( name )를, 가져온 값( james )으로 replace 하고

그렇게 만들어진 결과의 HTML 이 사용자에게 전달된다.

이런것을 바로 rendering 이라고 한다.

 

Flask 는 주어진 변수를 모두 replace 하면서 이 템플릿을 render 한다.

원하는 만큼 변수를 추가해서 사용할 수 있다. 그리고 그 변수를 HTML 에서 사용할 수 있다.


위 동작원리를 이용해서 age 변수 추가해보기

< main.py >

from flask import Flask, render_template

app = Flask("JobScrapper")

@app.route("/")
def home():
    return render_template("home.html", name="james", age=20)

@app.route("/hello")
def hello():
    return 'hello you!'

app.run("0.0.0.0")

< home.html >

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Job Scrapper</title>
</head>
<body>
    <h1>Hello to you! My name is {{name}}, I'm {{age}} years old</h1>
</body>
</html>

크롬창 새로 열고 주소창에 127.0.0.1:5000 입력 후 접속

 

 


python 참고 강의

https://nomadcoders.co/python-for-beginners/lobby

'Programming > Python 웹 스크래퍼 만들기' 카테고리의 다른 글

Python Flask 간단 정리  (0) 2022.12.30
Python Flask Form  (0) 2022.12.29
Python Flask Introduction  (0) 2022.12.27
Python webscrapper 완성  (0) 2022.12.08
Python webscrapper 파일 2개 합치기  (0) 2022.12.07
'Programming/Python 웹 스크래퍼 만들기' 카테고리의 다른 글
  • Python Flask 간단 정리
  • Python Flask Form
  • Python Flask Introduction
  • Python webscrapper 완성
Security Engineer
Security Engineer
IT 공부
Security Engineer
IT-log
Security Engineer
전체
오늘
어제
  • 분류 전체보기 (171)
    • Programming (39)
      • Python 웹 스크래퍼 만들기 (39)
    • IT 지식 (64)
      • IT 정보 (27)
      • CS 기초 (24)
      • 운영체제 (8)
      • IT 인프라 기초 (5)
    • 보안 (45)
      • 악성코드 분석 (10)
      • Bandit 워게임 (25)
      • 취미로 해킹 2 (6)
      • 환경 구축 (4)
    • 웹 해킹 (23)
      • 웹 기초 지식 (8)
      • SQL 기본 (2)
      • 웹 해킹 및 시큐어 코딩 기초 (13)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Beautifulsoup
  • 악성코드
  • Def
  • 해킹
  • flask
  • 모의해킹
  • 파이썬
  • CS 기초
  • webScrapper
  • Python
  • 리눅스
  • CS
  • 웹 개발
  • 시큐어 코딩
  • 취미로 해킹
  • Web
  • overthewire
  • HTML
  • 워게임
  • CSS
  • 웹 해킹
  • bandit
  • 컴퓨터
  • WarGame
  • 운영체제
  • IT 인프라
  • 악성코드 분석
  • 웹
  • Selenium
  • 취미로해킹

최근 댓글

최근 글

hELLO · Designed By 정상우.
Security Engineer
Python Flask Render Template
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.