티스토리 뷰
<코드 요약>
# 저장 - 예시
doc = {'name':'bobby','age':21}
db.users.insert_one(doc)
# 한 개 찾기 - 예시
user = db.users.find_one({'name':'bobby'})
# 여러개 찾기 - 예시 ( _id 값은 제외하고 출력)
all_users = list(db.users.find({},{'_id':False}))
# 바꾸기 - 예시
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})
# 지우기 - 예시
db.users.delete_one({'name':'bobby'})
<시작 코드>
from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.5hqkj.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta
<예제 1>
# mongoDB에서 영화 '가버나움'의 평점 가져오기
from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.5hqkj.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta
movie = db.movies.find_one({'title':'가버나움'})
print(movie['star'])
<예제 2>
# '가버나움'의 평점과 같은 평점의 영화 제목들을 가져오기
from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.5hqkj.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta
movie = db.movies.find_one({'title':'가버나움'})
star = movie['star']
all_movies = list(db.movies.find({'star': star}, {'_id':False}))
for m in all_movies:
print(m['title'])
여러 데이터를 뽑아낼 때, for문으로 돌린다..
<예제 3>
# '가버나움' 영화의 평점을 10으로 만들기
from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.5hqkj.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta
db.movies.update_one({'title':'가버나움'},{'$set':{'star':'10'}})
movie = db.movies.find_one({'title':'가버나움'})
print(movie['star'])
<예제 4 - request,bs4 복습>
# 지니뮤직 사이트에서 노래 순위/곡 이름/가수 스크래핑하기
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.5hqkj.mongodb.net/?retryWrites=true&w=majority')
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=M&rtm=N&ymd=20210701',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.title.ellipsis
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.number
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis
music = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for song in music:
a = song.select_one('a.title.ellipsis')
b = song.select_one('td.number')
c = song.select_one('td.info > a.artist.ellipsis')
title = a.text.strip()
rank = b.text[0:2].strip()
artist = c.text.strip()
if '19금' in title:
title = title.lstrip('19금').strip()
print(rank,'/', title,'/', artist)
# DB 저장
doc = {'rank': rank, 'title': title, 'artist': artist}
db.music.insert_one(doc)
# DB 출력
song = db.music.find_one({'title':'신호등'})
print(song['title'])
# 여러개 출력
all_music = list(db.music.find({'artist':'이무진'},{'_id':False}))
for m in all_music:
print(m['title'])
- 19금 노래 출력값에 공백이 있어 if문을 통해 없애주었다.
- text[0:2]를 통해 텍스트의 두번째 자리만 가져왔다.
- strip() 파이썬 내장함수를 통해 공백을 제거하였다.
'[학습일지] > Python' 카테고리의 다른 글
[학습일지] 웹개발 4-1 ~ 4-5 (파이썬, Flask를 사용해보자) (0) | 2022.07.25 |
---|---|
[학습일지] 웹개발 3-9 ( Python, requests/bs4) (0) | 2022.07.15 |
[학습일지] 웹개발 3-2 ~ 3-8 ( Python 입문, requests/bs4) (0) | 2022.07.14 |
[학습일지] 웹개발 3-1 ( Ajax, 영화 별점탭) (0) | 2022.07.13 |
[학습일지] 웹개발 2-14 ( Ajax, 날씨 정보) (0) | 2022.07.12 |