스파르타 강의 노트

고수진·2021년 5월 12일

bs4 스크래핑

# 타겟 URL을 읽어서 HTML를 받아오고,
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('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20200303',headers=headers)

# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦
# soup이라는 변수에 "파싱 용이해진 html"이 담긴 상태가 됨
# 이제 코딩을 통해 필요한 부분을 추출하면 된다.
soup = BeautifulSoup(data.text, 'html.parser')
#old_content > table > tbody > tr:nth-child(2) > td:nth-child(1) > img
#old_content > table > tbody > tr:nth-child(2) > td.point
trs = soup.select('#old_content > table > tbody > tr')
for tr in trs:
    a_tag = tr.select_one('td.title > div > a')
    if a_tag is not None:
        title = a_tag.text
        number = tr.select_one('td:nth-child(1) > img')['alt']
        grade = tr.select_one('td.point').text
        print(number, title,  grade)
        doc = {
            'number': number,
            'title': title,
            'grade': grade
        }
        db.movies.insert_one
        
        
trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for tr in trs:
    title = tr.select_one('td.info > a.title.ellipsis').text.strip()
    rank = tr.select_one('td.number').text
    ranks = rank[0:2].strip()
    star = tr.select_one('td.info > a.artist.ellipsis').text
    print(ranks, title, star)

import Flask + html templates

from flask import Flask, render_template
app = Flask(__name__)

## URL 별로 함수명이 같거나,
## route('/') 등의 주소가 같으면 안됩니다.

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

if __name__ == '__main__':
   app.run('0.0.0.0', port=5000, debug=True)

로딩후 바로 실행

$(document).ready(function () {
		alert('안녕!')
})

get 요청 --- 데이터 조회

#파이썬으로 요청
r = requests.get("https://owlbot.info/api/v4/dictionary/owl", headers={"Authorization": "Token [내토큰]"})
result = r.json()
print(result)

#ajax
@app.route('/test', methods=['GET'])
def test_get():
   title_receive = request.args.get('title_give')
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 GET!'})
  
  
$.ajax({
    type: "GET",
    url: "/test?title_give=봄날은간다",
    data: {},
    success: function(response){
       console.log(response)
    }
  })

Post 요청 --- 데이터 생성 변경 삭제

@app.route('/memo', methods=['POST'])
def post_articles():
		sample_receive = request.form['sample_give']
		print(sample_receive)
    return jsonify({'msg': 'POST 연결되었습니다!'})
    
    password_hash = hashlib.sha256(password_receive.encode('utf-8')).hexdigest() #해쉬
    
    
 function postArticle() {
  $.ajax({
    type: "POST",
    url: "/memo",
    data: {sample_give:'샘플데이터'},
    success: function (response) { // 성공하면
      alert(response['msg']);
    }
  })
}
    
  • 파일 업로드 기능
#서버Post에 추가
file = request.files["file_give"]

save_to = 'static/mypicture.jpg'
file.save(save_to)


#클라이언트
#부트스트랩 파일업로드 라이브러리
<script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script>

#get요청 전에 init함수호출
$(document).ready(function () {
            bsCustomFileInput.init()
            listing()
        })

#post 요청코드
function posting() {
    let title = $('#title').val()
    let content = $("#content").val()

    let file = $('#file')[0].files[0]
    let form_data = new FormData()

    form_data.append("file_give", file)
    form_data.append("title_give", title)
    form_data.append("content_give", content)

    $.ajax({
        type: "POST",
        url: "/diary",
        data: form_data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (response) {
            alert(response["msg"])
            window.location.reload()
        }
    });
}

fstring

name = '홍길동'
age = '23'
hello = f'제 이름은{name}입니다. 나이는 {age}입니다'
hello = '제 이름은'+name+'입니다. 나이는' +age+'입니다'

datetime 함수
참고

from datetime import datetime

today = datetime.now()
mytime = today.strftime('%Y-%m-%d-%H')
filename = f'file-{mytime}'
print(filename)

기타

window.location.reload()
profile
수진고

0개의 댓글