티스토리 뷰
6주차 과제
기본미션 : p.342[직접 해보는 손코딩:BeautifulSoup 스크레이핑 실행하기] 예제 실행 후 결과 화면 인증샷
from flask import Flask
from urllib import request
from bs4 import BeautifulSoup
app = Flask(__name__)
@app.route("/")
def hello():
#urlopen() 함수로 기상청의 전국 날씨를 읽는다
target = request.urlopen("http://www.kma.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108")
#BeautifulSoup를 사용해 웹페이지를 분석
soup = BeautifulSoup(target, "html.parser")
#location 태그를 찾는다
output = ""
for location in soup.select("location"):
#내부의 city, wf, tmn, tmx 태그를 찾아 출력함
output += "<h3>{}</h3>".format(location.select_one("city").string)
output += "날씨: {}<br/>".format(location.select_one("wf").string)
output += "최저/최고 기온: {}/{}"\
.format(\
location.select_one("tmn").string,\
location.select_one("tmx").string\
)
output += "<hr/>"
return output
set FLASK_APP=파일명.py
flask run
실행후 127.0.0.1:5000 local 접속!
예제 실행 인증샷
모듈 : 여러 변수와 함수를 가지고 있는 집합체. 크게 표준 모듈과 외부 모듈로 나뉜다.
- 표준 모듈 : 파이썬에 기본적으로 내장되어 있는 모듈
- 외부 모듈 : 다른 사람들이 만들어서 공개한 모듈
모듈 사용의 기본 : math 모듈
import math
math.sin(1)
random 모듈 : 랜덤값 생성
import random
print("# random 모듈")
#random(): 0.0 <= x < 1.0 사이의 float를 리턴함
print("- random():", random.random())
#uniform(min, max): 지정한 범위 사이의 float를 리턴함
print("- uniform(10, 20):", random.uniform(10,20))
#randrange(): 지정한 범위의 int를 리턴함
# - randrange(max): 0부터 max 사이의 값을 리턴함
# - randrange(min, max): min부터 max 사이의 값을 리턴함
print("- randrange(10):", random.randrange(10))
#choice(list): 리스트 내부에 있는 요소를 랜덤하게 선택함
print("- choice([1,2,3,4,5]):", random.choice([1,2,3,4,5]))
#choice(list): 리스트 내부에 있는 요소를 랜덤하게 섞음
print("- choice([1,2,3,4,5]):", random.shuffle([1,2,3,4,5]))
#sample(list, k=<숫자>): 리스트의 요소 중에 k개를 뽑습니다.
print("- sample([1,2,3,4,5], k=2):", random.sample([1,2,3,4,5], k=2))
sys 모듈 : 시스템과 관련된 정보를 가진 모듈
import sys
print(sys.argv)
print("---")
#컴퓨터 환경과 곤련된 정보를 출력함
print("getwindowsversion:()", sys.getwindowsversion())
print("---")
print("copyright:", sys.copyright)
print("---")
print("version:", sys.version)
#프로그램을 강제 종료함
sys.exit()
os 모듈 : 운영체제와 관련된 기능을 가진 모듈
import os
#기본 정보를 몇 개 출력해 봄
print("현재 운영체제:", os.name)
print("현재 폴더:", os.getcwd())
print("현재 폴더 내부의 요소:", os.listdir())
#폴더를 만들고 제거함.
os.mkdir("hello")
os.rmdir("hello")
#파일을 생성하고 + 파일 이름을 변경함
with open("original.txt", "w") as file:
file.write("hello")
os.rename("original.txt", "new.txt")
#파일을 제거함
os.remove("new.txt")
#os.unlik("new.txt")
#시스템 명령어 실행
os.system("dir")
datetime 모듈 : 날짜, 시간과 관련된 모듈
import datetime
#현재 시각을 구하고 출력하기
print("# 현재 시각 출력하기")
now = datetime.datetime.now()
print(now.year, "년")
print(now.month, "월")
print(now.day, "일")
print(now.hour, "시")
print(now.minute, "분")
print(now.second, "초")
print()
#시간 출력 방법
print("# 시간을 포맷에 맞춰 출력하기")
output_a = now.strftime("%Y.%m.%d %H:%M:%S")
output_b = "{}년 {}월 {}일 {}시 {}분 {}초".format(now.year,\
now.month,\
now.day,\
now.hour,\
now.minute,\
now.second)
output_c = now.strftime("%Y{} %m{} %d{} %M{} %S{}").format(*"년월일시분초")
print(output_a)
print(output_b)
print(output_c)
print()
import datetime
now = datetime.datetime.now()
print("#datetime.timedelta로 시간 더하기")
after = now + datetime.timedelta(\
weeks=1,\
days=1,\
hours=1,\
minutes=1,\
seconds=1)
print(after.strftime("%Y{} %m{} %d{} %H{} %M{} %S{}").format(*"년월일시분초"))
print()
#특정 시간 요소 교체하기
print("# now.replace()로 1년 더하기")
output = now.replace(year=(now.year + 1))
print(output.strftime("%Y{} %m{} %d{} %H{} %M{} %S{}").format(*"년월일시분초"))
time 모듈 : 시간과 관련된 기능을 다루는 모듈
import time
print("지금부터 5초 동안 정지합니다")
time.sleep(5)
print("프로그램을 종료합니다")
urllib 모듈 : url을 다루는 라이브러리
from urllib import request
target = request.urlopen("https://google.com")
output = target.read()
print(output)
교육도서 : 혼자 공부하는 파이썬 https://book.naver.com/bookdb/book_detail.nhn?bid=15028688
혼자 공부하는 파이썬
혼자 해도 충분하다! 1:1 과외하듯 배우는 파이썬 프로그래밍 자습서(파이썬 최신 버전 반영)27명의 베타리더 검증으로, ‘함께 만든’ 입문자 맞춤형 도서이 책은 독학으로 프로그래밍 언어를
book.naver.com
'Programming > Python' 카테고리의 다른 글
혼자 공부하는 파이썬 (0) | 2021.08.31 |
---|---|
[혼공챌린지]python 오류(Error) (0) | 2021.08.02 |
[혼공챌린지]python 함수 (0) | 2021.07.26 |
[혼공챌린지]python 자료형 (0) | 2021.07.19 |
[혼공챌린지]python 조건문 (0) | 2021.07.10 |
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- AWS
- EKS
- NW
- S3
- cni
- PYTHON
- operator
- 도서
- controltower
- AI
- IaC
- k8s cni
- 혼공파
- cloud
- OS
- k8s calico
- gcp serverless
- GKE
- NFT
- GCP
- 국제 개발 협력
- security
- SDWAN
- 파이썬
- VPN
- k8s
- 혼공챌린지
- terraform
- handson
- 혼공단
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함