본문 바로가기

항해99/웹 개발 종합반 강의

[스파르타코딩클럽] 웹개발 종합반 - 3주차 (3-9~15)

pip install requests bs4

를 통하여 웹 스크래핑 패키지 설치가 가능하다.

 

import requests
from bs4 import BeautifulSoup

URL = "https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query=날씨"
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')

이러한 형태로 soup에 웹페이지의 html 코드를 불러올 수 있다.

# 선택자를 사용하는 방법 (copy selector)
soup.select('태그명')
soup.select('.클래스명')
soup.select('#아이디명')

soup.select('상위태그명 > 하위태그명 > 하위태그명')
soup.select('상위태그명.클래스명 > 하위태그명.클래스명')

# 태그와 속성값으로 찾는 방법
soup.select('태그명[속성="값"]')

# 한 개만 가져오고 싶은 경우
soup.select_one('위와 동일')

 

soup에 있는 html의 데이터들을 불러오기 위해선 select, select_one을 사용하면 된다.

temp = soup.select_one('.temperature_text > strong').contents[1]
cloud = soup.select_one('.weather').text
humid = soup.select_one('.summary_list > div:nth-child(2) > dd').text
wind = soup.select_one('.summary_list > div:nth-child(3) > dd').text

print(temp, cloud, humid, wind)

이런 형식으로. text와. contents를 사용하여 내부 글자들/ 리스트로 추출할 수 있다.

 

 

이후 Flask에 대하여 배우게 됐다.

Flask는 구조가 정해져 있는데,

flask

|— venv

|— app.py (서버)

|— templates |— index.html (클라이언트 파일)

이러한 형식이다.

 

이후 pip install flask를 통하여 설치를 하게 되면 로컬 호스트 사이트를 생성할 수 있게 된다.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return 'This is Home!'

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

@app. route('/') 이 부분이 바로 주소를 지정해 주는 부분이며, 여기 아랫줄에 관련된 함수를 넣어주면 되는 형식이다.

 

templates에 있는 html파일을 불러오기 위해선

from flask import Flask, render_template를 통하여 return render_template('index.html')라고 해주면 된다.

 

python 파일에서 원하는 데이터를 html로 넘겨줄 수가 있다.

방법은 바로 render_template('index.html', data = name)과 같은 형식으로 코드를 주가 해주면 된다.

 

여러 개의 데이터를 넘겨주려는 경우엔, list와 dictonary를 사용해 주면 된다.

html에서도 반복문을 사용해 줄 수 있는데, 그 방법은 아래와 같다.

<body>
    <h1>안녕, {{ data.name }}</h1>
    <h2>로또 번호: {{ data.lotto }}</h2>

    {% for number in data.lotto %}
            {{ number }}
    {% endfor %}
</body>

 

반대로 html로부터 python으로 데이터를 받기 위해선 form을 만들어주면 된다.

<form action="{{ url_for('movie') }}">
  <input type="text" name="query">
  <button type="submit">검색</button>
</form>

python 파일에서 이 검색어를 받기 위해선 request를 import 해준 후 사용해 주면 된다.

from flask import Flask, render_template, request


@app.route('/movie')
def movie():
    print(request.args.get('query'))
    return render_template('movie.html')