1. 2주차 복습_Open API
$(document).ready(function(){
listing();
});
$(document).ready(function () {
$('#id').empty();
listing();
});
2. 파이썬 기초공부
a = 3 # 3을 a에 넣는다
b = a # a를 b에 넣는다
a = a + 1 # a+1을 다시 a에 넣는다
num1 = a*b # a*b의 값을 num1이라는 변수에 넣는다
num2 = 99 # 99의 값을 num2이라는 변수에 넣는다
# 변수의 이름은 마음대로 지을 수 있음!
name = 'bob' # 변수에는 문자열이 들어갈 수도 있고,
num = 12 # 숫자가 들어갈 수도 있고,
is_number = True # True 또는 False -> "Boolean"형이 들어갈 수도 있다.
리스트 형: []은 배열이다.
a_list = []
a_list.append(1) # 리스트에 값을 넣는다
a_list.append([2,3]) # 리스트에 [2,3]이라는 리스트를 다시 넣는다
# a_list의 값은? [1,[2,3]]
# a_list[0]의 값은? 1
# a_list[1]의 값은? [2,3]
# a_list[1][0]의 값은? 2
Dictionary 형: {}은 시작과 끝을 의미.
a_dict = {}
a_dict = {'name':'bob','age':21}
a_dict['height'] = 178
# a_dict의 값은? {'name':'bob','age':21, 'height':178}
# a_dict['name']의 값은? 'bob'
# a_dict['age']의 값은? 21
# a_dict['height']의 값은? 178
Dictionary 형과 List형의 조합
people = [{'name':'bob','age':20},{'name':'carry','age':38}]
# people[0]['name']의 값은? 'bob'
# people[1]['name']의 값은? 'carry'
person = {'name':'john','age':7}
people.append(person)
# people의 값은? [{'name':'bob','age':20},{'name':'carry','age':38},{'name':'john','age':7}]
# people[2]['name']의 값은? 'john'
def aa(num1,num2):
return num1+num2
result = aa(2,3)
print(result)
출력해보면 당연히 값으로 5가 나온다.
예제 1
age = 30
if age > 20:
print('성인입니다.')
else:
print('청소년입니다.')
실행 시 '성인입니다.'가 결과값으로 출력.
예제 2
def is_adult(age):
if age > 20:
print('성인입니다') # 조건이 참이면 성인입니다를 출력
else:
print('청소년이에요') # 조건이 거짓이면 청소년이에요를 출력
is_adult(30)
실행 시 '성인입니다.'가 결과값으로 출력.
예제1
fruits = ['사과','배','감','귤']
for fruit in fruits:
print(fruit)
# 사과, 배, 감, 귤 하나씩 꺼내어 찍힙니다.
예제2
def count_fruits(target):
count = 0
for fruit in fruits:
if fruit == target:
count += 1
return count
subak_count = count_fruits('수박')
print(subak_count) #수박의 개수
gam_count = count_fruits('감')
print(gam_count) #감의 개수
예제3
people = [{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27}]
# 모든 사람의 이름과 나이를 출력해봅시다.
for person in people:
print(person['name'], person['age'])
# 이번엔, 반복문과 조건문을 응용한 함수를 만들어봅시다.
# 이름을 받으면, age를 리턴해주는 함수
def get_age(myname):
for person in people:
if person['name'] == myname:
return person['age']
return '해당하는 이름이 없습니다'
print(get_age('bob'))
print(get_age('kay'))
3. requests 패키지 사용해보기
0번째 배열의 NO2값 출력할 때
import requests
r = requests.get('http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99')
rjson = r.json()
print(rjson['RealtimeCityAir']['row'][0]['NO2'])
모든 구의 IDEX_MVL 값을 찍을 때
import requests # requests 라이브러리 설치 필요
r = requests.get('http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99')
rjson = r.json()
gus = rjson['RealtimeCityAir']['row']
for gu in gus:
print(gu['MSRSTE_NM'], gu['IDEX_MVL'])
IDEX_MVL 값이 60 미만인 구만 찍을 때
import requests # requests 라이브러리 설치 필요
r = requests.get('http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99')
rjson = r.json()
gus = rjson['RealtimeCityAir']['row']
for gu in gus:
if gu['IDEX_MVL'] < 60:
print (gu['MSRSTE_NM'], gu['IDEX_MVL'])
4. 웹스크래핑(크롤링) 기초
import requests
from bs4 import BeautifulSoup
# 타겟 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')
#############################
# (입맛에 맞게 코딩)
#############################
import requests
from bs4 import BeautifulSoup
# 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 = BeautifulSoup(data.text, 'html.parser')
# select를 이용해서, tr들을 불러오기
movies = soup.select('#old_content > table > tbody > tr')
# movies (tr들) 의 반복문을 돌리기
for movie in movies:
# movie 안에 a 가 있으면,
a_tag = movie.select_one('td.title > div > a')
if a_tag is not None:
# a의 text를 찍어본다.
print (a_tag.text)
# 선택자를 사용하는 방법 (copy selector)
soup.select('태그명')
soup.select('.클래스명')
soup.select('#아이디명')
soup.select('상위태그명 > 하위태그명 > 하위태그명')
soup.select('상위태그명.클래스명 > 하위태그명.클래스명')
# 태그와 속성값으로 찾는 방법
soup.select('태그명[속성="값"]')
# 한 개만 가져오고 싶은 경우
soup.select_one('위와 동일')
크롬 개발자도구를 참고하면 코드 쓰기 더 좋다.
5. pymongo로 DB조작하기
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
# 코딩 시작
한 개 찾기
user = db.users.find_one({'name':'bobby'})
여러개 찾기
same_ages = list(db.users.find({'age':21},{'_id':False}))
바꾸기
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})
지우기
db.users.delete_one({'name':'bobby'})
for music in musics:
title = music.select_one
For 다음에 오는 항목은 .select_one앞 문자와 반드시 일치!!
music.select_one(‘’) -> ‘검사'에서 찾은 값 붙여넣을 때 ‘’ 무조건 씀!!
항상 작성 후 Print(xx)로 출력해보고, text만 나오게 하고 싶으면 print(xx.text) .text무조건 붙임
파이썬 공백 없애기: .strip()
파이썬 문자열 자르기 : .string[0:2].strip() 여기서 문자는 hello world라면 0:공백, 1:h, 2:e, 3:l, 4:l, 5:o 의 순서로(컴퓨터는 모든 order가 0부터 시작)