- 파이참 : html은 open으로, python은 new project로 열기
- venv는 절대 손대지 말 것
- 파이썬 ~~~ 패키지 로 검색하면 많은 자료 나옴
ajax 복습
<script>
$(document).ready(function () {
listing();
});
</script>
- 지우기 (예시로 되어 있던 카드, 리스트 등 지우기)
<script>
$('#id값').empty()
</script>
<script>
for (let i = 0; i < ~~~.length; i++) {
</script>
<script>
let temp_html = `붙힐 html 긁어와서 해당 자리에 ${~~}`
$('#id').append(temp_html)
</script>
파이썬
- 변수
- 자료형 : 숫자형, 문자형, 리스트형, 딕셔너리형
- 숫자형을 문자형으로 바꿀 때에는 str(숫자)
- 리스트형 추가 : 리스트명.append(추가할 내용)
- 딕셔너리형 추가 : 딕셔너리명[key] = value
- 함수
def aa1(a,b,c):
return a+b+c
def aa2(a,b):
return a*b
result = aa1(1,2,3) + aa2(10,10)
print(result)
106
- 조건문
- 반복문
a = [1,2,3,4]
for aa in a:
print(a)
fruits = ['사과','배','배','감','수박','귤','딸기','사과','배','수박']
count = 0
for fruit in fruits:
if fruit == '사과':
count += 1
print(count)
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)
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'])
def get_age(myname):
for person in people:
if person['name'] == myname:
return person['age']
return '해당하는 이름이 없습니다'
print(get_age('bob'))
print(get_age('kay'))
20
해당하는 이름이 없습니다
requests 패키지
import 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:
gu_name = gu['MSRSTE_NM']
gu_mise = gu['IDEX_MVL']
if gu_mise > 50:
print(gu_name,gu_mise)
미세먼지값이 50보다 큰 구와 미세먼지의 값이 쭉 찍힘
크롤링(웹스크래핑)
- bs4 패키지 필요
- 요청 : requests / 솎아내기 : beautifulsoup (bs4)
- select : 다 가져오는 것
- select_one : 하나만 가져오는 것
- 해당 태그의 글자만 가져오고 싶을 때
- 해당 태그의 속성을 가져오고 싶을 때
- None이 있을 때 .text로 가져오면 에러발생
if aaa is not None:
print(aaa.text)
이렇게 none이 아닐 때라고 if문으로 해줘야함
- 크롤링 연습
- 개발자도구 → 해당 태그 copy → copy selector → 뒤에 다른 부분 지우고 soup.select('여기에 넣기')
- 뽑아 올 것은 soup.select 안에 있는 겹치는 부분 제외한 다음에 오는 부분 넣기
import requests
from bs4 import BeautifulSoup
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)
soup = BeautifulSoup(data.text, 'html.parser')
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:
rank =tr.select_one('td:nth-child(1) > img')['alt']
title = a_tag.text
star = tr.select_one('td.point').text
print(rank, title, star)
DB
- DB를 쌓아두는 것
- 내 눈에 보이지 않게 켜짐
- ROBO 3T는 mongoDB 시각화해서 눈으로 볼 수 있게 하는 프로그램
- SQL : 엑셀형태
- 일관성O, 데이터 분석에 용이
- MS-SQL, MY-SQL ...
- NoSQL : 딕셔너리형태
- 자유로운 데이터 적재, 일관성 부족
- MongoDB
pymongo 기본코드
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
- dbprac에서 복사해서 알맞게 고쳐서 사용
doc = {'name':'bobby','age':21}
db.users.insert_one(doc)
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'})
- {'_id':False} → id값은 가져오지 않는다는 것
크롤링 Quiz
- 매트릭스 평점 가져오기
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
a_movie = db.movies.find_one({'title':'매트릭스'})
print(a_movie['star'])
- 매트릭스 평점과 같은 평점의 영화 제목 가져오기
a_movie = db.movies.find_one({'title':'매트릭스'})
a_star = a_movie['star']
movies = list(db.movies.find({'star':a_star},{'_id':False}))
for movie in movies:
print(movie['title'])
- 매트릭스 평점 0점으로 만들기
db.movies.update_one({'title':'매트릭스'},{'$set':{'star':str(0)}})
- 지니뮤직 스크래핑
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
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://www.genie.co.kr/chart/top200?ditc=D&rtm=N&ymd=20221010',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for tr in trs:
rank =tr.select_one('td.number').text[0:2].strip()
title = tr.select_one('td.info > a.title.ellipsis').text.strip()
artist = tr.select_one('td.info > a.artist.ellipsis').text
print(rank, title, artist)