Jaegool_'s log

웹개발 종합반 3주차 내용 [스파르타 코딩] <Python, crawling, mongoDB> 본문

Development Log/Web Development

웹개발 종합반 3주차 내용 [스파르타 코딩] <Python, crawling, mongoDB>

Jaegool 2022. 5. 21. 00:39

https://teamsparta.notion.site/3-baced734e9a44ffc9fd96e2ab6ad34f7

 

[스파르타코딩클럽] 웹개발 종합반 - 3주차

매 주차 강의자료 시작에 PDF파일을 올려두었어요!

teamsparta.notion.site

 

<Crawling을 위한 BeautifulSoup 기본 코드>

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')

** data = requests.get('URL', headers=headers)

 

 

<pymongo 기본 코드>

from pymongo import MongoClient
client = MongoClient('여기에 URL 입력')
db = client.dbsparta

pymongo의 기본 코드는 위와 같았지만 내 Mac의 경우(혹은 사용하고 있는 인터넷에 따라) 보안 관련 추가 설정이 필요했다.

 

>> certifi 패키지를 추가 설치 후

from pymongo import MongoClient
import certifi

ca = certifi.where()
client = MongoClient('mongodb+srv://test:sparta@cluster0.l0equ.mongodb.net/Cluster0?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta

certifi 관련 코드를 추가로 더 작성해주어야 했다.

client = MongoClient('', tlsCAFile=ca)

 

 

<숙제>

지니 웹사이트를 이용해서 순위, 곡명, 가수명을 크롤링하기.

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')

songs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')

for song in songs:
    rank = song.select_one('td.number').text[0:2].strip()
    title = song.select_one('td.info > a.title.ellipsis').text.strip()
    if "19금" in title:
        title = "19금 " + song.select_one('td.info > a.title.ellipsis').text.strip().lstrip('19금').strip()
    singer = song.select_one('td.info > a.artist.ellipsis').text
    print(rank, title, singer)

 

<Problem>

BeautifulSoup을 사용할 때 for문을 돌리기전에

songs = soup.select('#body-content > div.newest-list > div > table > tbody > tr')

이 부분에서 'select'를 'select_one()'으로 작성해서 한참을 어디서 잘못되었는지 찾아보았다.

>>> 전체선택후 하나씩 할당해주기!!

 

숙제를 해결하는 과정에서 'title'에 원하지 않는 정보(19금 icon)때문에 여백이 크게 발생하는 issue가 있었다.

위를 해결하기 위해서 lstrip('str').strip()을 활용하는 법을 새로 익혔다.

lstrip('str')로 좌측에 있는 필요없는 문자열을 제거한 후 다시 strip()을 이용하여 여백을 제거,

데이터를 사용하기 편하게 만들어 줄 수 있었다.