스파르타코딩클럽 웹개발종합반 #NOTE 4

Jenny Park·2022년 1월 10일
0

4주차 수업을 마치며

도통 감이 오지 않는 기분이다. 이제 배웠던 모든 것을 총 집합해서 사용하는 기분인데 이전 내용들이 가물가물한 기분에다가 만든다기보다 같이 써내려가기 바쁜 것 같다. 그나마 다행인 건 왜 그 코딩을 가져와서 사용하는지에 대해서는 알고 있다는 것. 그러나 4주차 숙제가 제일 어렵고 제일 구동이 되지 않아서 골이 아팠다. (평균적으로 다른 숙제는 1시간 내에 끝이 났건만 이번 숙제는 2시간을 끙끙 거렸음에도 불구하고 나오질 않는다. 심지어 따라쓰기도 해봤으나 안됌..)

  • Sever setting & API 설계 등

가장 먼저 static, templates 폴더+app.py 생성 (index.html까지!)

  • meta 태그 스크래핑 기초세팅 (meta_prac.py)

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)
1. 서버부터 만들기!
meta tag, url 등을 확인하여 입력하는 것이 중요!
@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)
2. 클라이언트 만들기!
어떤 정보를 어디서 가져와서 DB를 만들거나 입력한 데이터를 어떻게 저장할 것인지 고민이 필요!
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에 저장할 뿐만 아니라
목록으로 보여주기까지 할 수 있음!

오늘의 함정 : 아직도 숙제중이라는 대함정....OTL

profile
글도, 코드도 열심히 :)

0개의 댓글