brew 설치
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
mongoDB 설치
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community
mongoDB 실행
brew services start mongodb-community
성공시 아래와 같은 Port로 연결된다.
mongo DB 중지
brew services stop mongodb-community
패키지?Library란?
Python에서 패키지는 모듈(일종의 기능들 묶음)을 모아 놓은 단위이다.
이런 패키지의 묶음을 Library라고 하며 외부 Library를 사용하기 위해서 패키지를 설치해야 한다.
venv(가상환경)이란?
프로젝트마다 Library가 다를 수도 있고, 버전이 다를 수도 있으므로 패키지를 담아놓는 가상의 공간.
API를 가져오기
requests
import requests #requests 라이브러리 필요 r = requests.get('URL') rjson = r.json() print(rjson)
크롤링에 필요한 패키지
bs4 (beautiful soup4)
import requests from bs4 import BeautifulSoup # 코드단에서의 요청을 막아둔 사이트를 우회하려고 headers사용. 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) # 걸러내기 쉬운 bs형식으로 return soup = BeautifulSoup(data.text, 'html.parser')
title =
soup.select_one(#old_content > table > tbody > tr:nth-child(2) > td.title > div > a)
print(title.text) #tag의 text를 가져옴
print(title['href']) #tag의 속성을 가져옴
#old_content > table > tbody > tr:nth-child(2)
#old_content > table > tbody > tr:nth-child(3)
코드가 서로 다르므로 전체를 가져오려면
#old_content > table > tbody > tr 을 활용
#old_content > table > tbody > tr:nth-child(2) #old_content > table > tbody > tr:nth-child(3) #old_content > table > tbody > tr:nth-child(2) > td.title > div > a trs = soup.select('#old_content > table > tbody > tr') # 결과가 list로 반환된다. for tr in trs: title_tag = tr.select_one('td.title>div>a') if(title_tag): print(title_tag.text)
from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client.practice #사용할 DB_name .. 없으면 create # 코딩 시작
insert
#저장
doc = {'name':'yoon','age':25}
db.users.insert_one(doc)
같은 데이터를 넣어도 hash?값이 다르기 때문에 다른 객체로 판단한다.
find
#한 개 찾기
user = db.users.find_one({'name':'yoon'})
동명이인(같은Key)일 경우 가장 앞에 저장되어 있는 것을 반환
#여러개 찾기(_id값은 제외하고 출력)
users = list(db.users.find({'name':'bobby'},{'_id':False}))
for i in users: print(i)
#저장되어 있는 것 모두 확인하기
users = list(db.users.find({},{'_id':False}))
for i in users: print(i)
update
#한 개 수정
db.users.update_one({'name':'yoon'},{'$set':{'age':19}})
해당 Key로 찾은 가장 앞에 있는 것을 수정
#여러개 수정
db.users.update_many({'name':'yoon'},{'$set':{'age':19}})
delete(DB에서 삭제는 잘 일어나지 않는다.)
#한 개 삭제
db.users.delete_one({'name':'yoon'})
#여러개 삭제
db.users.delete_many({'name':'yoon'})