import requests
from bs4 import BeautifulSoup
url = 'https://movie.naver.com/movie/bi/mi/basic.naver?code=191597'
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(url,headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
# 여기에 코딩을 해서 meta tag를 먼저 가져와보겠습니다.
# meta의 property가 "og:title", "og:image", "og:description" 인 것을 가져오는 코드
title = soup.select_one('meta[property="og:title"]')['content']
image = soup.select_one('meta[property="og:image"]')['content']
desc = soup.select_one('meta[property="og:description"]')['content']
1) 크롤링을 해서 제목, 줄거리, 별점을 가져옴
# meta의 property가 "og:title", "og:image", "og:description" 인 것을 가져오는 코드
title = soup.select_one('meta[property="og:title"]')['content']
image = soup.select_one('meta[property="og:image"]')['content']
desc = soup.select_one('meta[property="og:description"]')['content']
2) url(title, image, desc), star, comment를 받음
url_receive = request.form['url_give']
star_receive = request.form['star_give']
comment_receive = request.form['comment_give']
data = requests.get(url_receive, headers=headers)
3) DB에 저장하는 코드 작성
doc = {
'title': title,
'image': image,
'desc': desc,
'star': star_receive,
'comment': comment_receive,
}
db.movies.insert_one(doc)
4) index.html 파일에서 버튼을 눌렀을 때 posting 함수 작동시키기,
function posting() {
let url = $("#url").val()
let star = $("#star").val()
let comment = $("#comment").val()
$.ajax({
type: 'POST',
url: '/movie',
data: {url_give:url, star_give:star, comment_give:comment},
success: function (response) {
alert(response['msg'])
window.location.reload();
}
});
}
5) 키 moives로 가져가고 데이터는 moive_list(DB에 저장된 데이터) 그대로 가져감
movie_list = list(db.movies.find({}, {'_id': False}))
@app.route("/movie", methods=["GET"])
def movie_get():
movie_list = list(db.movies.find({}, {'_id': False}))
return jsonify({'movies': movie_list})
6) response = {'movies': movie_list}
7) 반복문을 사용하여 row의 길이만큼 반복
8) title, image, desc, star, comment를 변수에 저장
let star_image = '⭐'.repeat(star)
9) $("#아이디값").append(변수)를 사용하여 화면에 나타냄
function listing() {
$.ajax({
type: 'GET',
url: '/movie',
data: {},
success: function (response) {
let rows = (response['movies'])
for (let i = 0; i < rows.length; i++) {
let comment = rows[i]["comment"]
let title = rows[i]["title"]
let desc = rows[i]["desc"]
let star = rows[i]["star"]
let image = rows[i]["image"]
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)
}
}
})
}
숙제하면서 느낀점
1) 오타 확인을 잘해야한다. (), #, "", 같은 것들 특히 주의해야 함!!
2) return 밑에 코드를 쓰니 코드가 작동되지 않았음, return 코드가 실행되면 그 뒤에 코드는 실행이 안되니 주의할 것!!!!
순서
1) name, comment를 jQuery로 가져옴
2) 데이터를 name_give, comment_give로 보냄
function save_comment() {
let name = $("#name").val();
let comment = $("#comment").val();
// 오타 확인 잘하자 () 없어서 20분 허덕임
$.ajax({
type: 'POST',
url: '/homework',
data: {comment_give:comment, name_give:name},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}
3) 데이터를 받고 DB에 저장을 함
4) '저장 완료!'라는 메시지를 alert로 보여주고 새로고침함
@app.route("/homework", methods=["POST"])
def homework_post():
comment_receive = request.form['comment_give']
name_receive = request.form['name_give']
doc = {
'comment': comment_receive,
'names': name_receive,
}
db.comments.insert_one(doc)
return jsonify({'msg': '저장 완료!'})
# ! 리턴은 마지막에 쓰자, 그 뒤에 코드가 실행이 안됨. 이거땜에 10분 까먹음
5) DB에 저장된 데이터를 여러개 가져옴
6) 가져온 데이터를 comment_list 변수에 저장해 index.html로 보냄
@app.route("/homework", methods=["GET"])
def homework_get():
comment_list = list(db.comments.find({}, {'_id': False}))
return jsonify({'comments': comment_list})
7) response = {'comments': comment_list}
8) 반복문을 사용하여 row의 길이만큼 반복
9) name, comment를 변수에 저장
10) $("#아이디값").append(변수)를 사용하여 화면에 나타냄
function show_comment() {
$('#comment-list').empty()
$.ajax({
type: "GET",
url: "/homework",
data: {},
success: function (response) {
let rows = response['comments']
console.log(response['comments'])
for (let i = 0; i < rows.length; i++) {
let comment = rows[i]['comment']
let names = rows[i]['names']
temp_html = `<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${comment}</p>
<footer class="blockquote-footer">${names}</footer>
</blockquote>
</div>
</div>`
$("#comment-list").append(temp_html);
}
}
});
}
# app.py 파일
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.wsolap1.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
@app.route('/')
def home():
return render_template('index.html')
@app.route("/homework", methods=["POST"])
def homework_post():
comment_receive = request.form['comment_give']
name_receive = request.form['name_give']
doc = {
'comment': comment_receive,
'names': name_receive,
}
db.comments.insert_one(doc)
return jsonify({'msg': '저장 완료!'})
# ! 리턴은 마지막에 쓰자, 그 뒤에 코드가 실행이 안됨. 이거땜에 10분 까먹음
@app.route("/homework", methods=["GET"])
def homework_get():
comment_list = list(db.comments.find({}, {'_id': False}))
return jsonify({'comments': comment_list})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
// index.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">
<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>초미니홈피 - 팬명록</title>
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+KR:wght@200;300;400;500;600;700;900&display=swap"
rel="stylesheet">
<style>
* {
font-family: 'Noto Serif KR', serif;
}
.mypic {
width: 100%;
height: 300px;
background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://cdn.topstarnews.net/news/photo/201912/714847_426867_3336.jpeg');
background-position: center 70%;
background-size: cover;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.mypost {
width: 95%;
max-width: 500px;
margin: 20px auto 20px auto;
box-shadow: 0px 0px 3px 0px black;
padding: 20px;
}
.mypost > button {
margin-top: 15px;
}
.mycards {
width: 95%;
max-width: 500px;
margin: auto;
}
.mycards > .card {
margin-top: 10px;
margin-bottom: 10px;
}
</style>
<script>
$(document).ready(function () {
set_temp()
show_comment()
});
function set_temp() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
success: function (response) {
$('#temp').text(response['temp'] + "도")
}
})
}
function save_comment() {
let name = $("#name").val();
let comment = $("#comment").val();
// 오타 확인 잘하자 () 없어서 20분 허덕임
$.ajax({
type: 'POST',
url: '/homework',
data: {comment_give:comment, name_give:name},
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}
function show_comment() {
$('#comment-list').empty()
$.ajax({
type: "GET",
url: "/homework",
data: {},
success: function (response) {
let rows = response['comments']
console.log(response['comments'])
for (let i = 0; i < rows.length; i++) {
let comment = rows[i]['comment']
let names = rows[i]['names']
temp_html = `<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${comment}</p>
<footer class="blockquote-footer">${names}</footer>
</blockquote>
</div>
</div>`
$("#comment-list").append(temp_html);
}
}
});
}
</script>
</head>
<body>
<div class="mypic">
<h1>아이유(IU) 팬명록</h1>
<p>현재기온: <span id="temp"></span></p>
</div>
<div class="mypost">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="name" placeholder="url">
<label for="name">닉네임</label>
</div>
<div class="form-floating">
<textarea class="form-control" placeholder="Leave a comment here" id="comment"
style="height: 100px"></textarea>
<label for="comment">응원댓글</label>
</div>
<button onclick="save_comment()" type="button" class="btn btn-dark">응원 남기기</button>
</div>
<div class="mycards" id="comment-list">
</div>
</body>
</html>