도통 감이 오지 않는 기분이다. 이제 배웠던 모든 것을 총 집합해서 사용하는 기분인데 이전 내용들이 가물가물한 기분에다가 만든다기보다 같이 써내려가기 바쁜 것 같다. 그나마 다행인 건 왜 그 코딩을 가져와서 사용하는지에 대해서는 알고 있다는 것. 그러나 4주차 숙제가 제일 어렵고 제일 구동이 되지 않아서 골이 아팠다. (평균적으로 다른 숙제는 1시간 내에 끝이 났건만 이번 숙제는 2시간을 끙끙 거렸음에도 불구하고 나오질 않는다. 심지어 따라쓰기도 해봤으나 안됌..)
가장 먼저 static, templates 폴더+app.py 생성 (index.html까지!)
import requests
from bs4 import BeautifulSoup
url = 'https://movie.naver.com/movie/bi/mi/basic.nhn?code=171539'
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')
↓ 어떤 내용을 select를 할 것인지를 파악하고, 찾는 것이 중요합니다.
그래야 정확한 tag name을 확인하여 코딩에 오류가 없도록 해야함.
(크롬의 '검사' 기능을 잘 활용하는 것이 생각보다 중요! + console)
og_image = soup.select_one('meta[property="og:image"]')
og_title = soup.select_one('meta[property="og:title"]')
og_description = soup.select_one('meta[property="og:description"]')
print(og_image)
print(og_title)
print(og_description)
@app.route('/memo', methods=['POST'])
def saving():
url_receive = request.form['url_give']
comment_receive = request.form['comment_give']
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_receive, headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
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']
doc = {
'title':title,
'image':image,
'desc':desc,
'url':url_receive,
'comment':comment_receive
}
db.articles.insert_one(doc)
function postArticle() {
let url = $('#post-url').val()
let comment = $('#post-comment').val()
$.ajax({
type: "POST",
url: "/memo",
data: {url_give:url, comment_give:comment},
success: function (response) { // 성공하면
alert(response["msg"]);
window.location.reload()
}
})
}
"POST"부분은 "Get"으로 변경하여 입력된 정보를 DB에 저장할 뿐만 아니라
목록으로 보여주기까지 할 수 있음!