티스토리 뷰

이번에는 간단한 restful server를 만들어서, 입력된 tag의 갯수를 화면에 표시해주는 프로그램을 짜보자

일단 flask를 설치하고 (pip install flask)

 

기본 경로 옆에 templates라는 폴더를 만들고 그 안에 hello.html 을 만들어서 아래와 같은 내용으로 채운다

<html>
<body>
{{count}}
</body>
</html>

위의 {{count}} 부분에 tag 갯수를 표시해 줄 것이다.

 

이제 이전편에 짠 파서를 이용해서 아래와 같은 코드를 작성하자

 

from flask import Flask, render_template, request
from bs4 import BeautifulSoup
import selenium.webdriver as webdriver

app = Flask(__name__)

@app.route('/get_tag')
def get_tag_count():
    tag = request.args.get('tag')
    print(tag)
    url = "https://www.instagram.com/explore/tags/" + tag
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    options.add_argument('disable-gpu')
    driver = webdriver.Chrome('chromedriver', chrome_options=options)
    driver.get(url)
    soup = BeautifulSoup(driver.page_source, "html.parser")
    span_tag = soup.find("span",{"class": "g47SY "})
    count = span_tag.text
    print(count)
    return render_template('hello.html',count=count)

if __name__ == '__main__':
    app.run()

 

이게 뭐냐면..

@app.route('/get_tag')를 통해서

http://127.0.0.1:5000/get_tag

를 통해 접속하는 것이 가능해 졌다는 뜻이고,

request.args.get('tag') 를 통해

http://127.0.0.1:5000/get_tag?tag=jmt

위 처럼 GET parameter를 넣는게 가능해 졌다는 말임.

def 제일 아래의

return render_template('hello.html',count=count)

위 코드를 통해 hello.html 페이지의 count 값에 count를 넣어준 것임.

위를 실행(python main.py) 한 후

http://127.0.0.1:5000/get_tag?tag=jmt

를 치면 정상적으로 jmt의 태그 갯수가 표시되는걸 볼 수 있다.

 

문제 중 하나는 파라미터가 한글이면 동작이 안된다... 어찌 해결해야할 것인가 ;ㅅ;

그리고 이걸 실 적용하기엔 너무 느리다 흑흑 (셀레늄으로 렌더 하고 파싱하고...)

결국엔 일정 스케쥴에 따라 서비스가 돌면서 DB에 위 값을 저장해 주고, 실제 사용자가 rest api 호출 시에는 해당 db에서 값을 보여주는.. 그런 서버가 하나 있어야 쓰겄다.

천천히 공부하며 짜보자.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함