DB 연결하기
DB Atlas 사용시, pymongo.errors.ServerSelectionTimeoutError: ~ [SSL: CERTIFICATE_VERIFY_FAILED]~ 를 포함한 에러 메시지가 뜨면서 실행이 되지 않았다.
문제는 사용하고 있는 인터넷 환경에 따라 보안 관련 추가 설정을 해주어야할 때가 있어 보안관련 설정을 추가로 해주어야 한다고 한다.

환경설정에서 certifi를 설치해주고
from pymongo import MongoClient
import certifi
ca = certifi.where()
client = MongoClient('mongodb+srv://haroe:패스워드@cluster0.jbeqc4x.mongodb.net/Cluster0?retryWrites=true&w=majority',tlsCAFile=ca)
db = client.dbsparta
doc = {
'name':'bob',
'age':27
}
db.users.insert_one(doc)
특히 client = MongoClient 부분 코드 맨 끝에 있는 tlsCAFile=ca 를 추가를 꼭 해주어야 한다 !
이렇게 하면 내 DB연결이 정상적으로 이루어 진다.
pymongo로 DB조작하기
# 저장 - 예시
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'})
웹스크래핑결과 이용하기

뮤직 차트에서 순위, 제목, 아티스트를 나오게 하라
먼저 기본적으로 웹사이트 내역을 가져오는 코드를 세팅해둔다.
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://www.genie.co.kr/chart/top200?ditc=M&rtm=N&ymd=20210701',headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')
다음으로 순위 내역을 가져와야 하므로 순위에 검사 - selector복사를 누르면
#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(2) > td.number
1순위와 2순위에 tr까지는 코드가 같다는 것을 확인할 수 있다.
그래서 이름을 임의로 trs로 설정해둔 뒤에 위 soup에서 이 값을 선택해준다.
trs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
다음으로 tr안에 trs를 넣어 rank를 설정하고 뒷부분에 같았던(td.number)를 넣어준다.
이것을 text로 변형해서 출력해준 뒤에 여기까지만 해서 print로 출력해서 본다면 뒤죽박죽인 숫자가 보이기 때문에 text[0:2] 0부터 2까지로 끊어준 다음 공백을 제거할 수 있는 strip()를 써줘서 해결한다.
for tr in trs:
rank = tr.select_one('td.number').text[0:2].strip()
위와 같이 제목과 아티스트 또한 print로 한개 한개씩 만들때 공백이 있는지 확인한 다음
마지막에 print된 항목들을 다 출력하면 오늘의 숙제는 완료다!
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)