Sparta/스파르타코딩 웹개발 종합반

웹개발 종합반 3주차 - Python 크롤링, DB 연결

또롱또 2022. 2. 3. 07:18
728x90

Python, MongoDB

 

Python 패키지 설치

- requests

request 패키지는 가장 많이 사용하는 라이브러리중 하나이며
request를 이용하면 쉽게 http 요청을 보낼수 있습니다.

(HTML 문서에 담긴 내용을 가져 오도록 request(요청) 해야 한다)

 

- bs4

HTML 문서를 탐색해서 원하는 부분만 쉽게 뽑아낼 수 있는 파이썬 라이브러리 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('내가 크롤링 할 사이트 주소',headers=headers)

soup = BeautifulSoup(data.text, 'html.parser')

 

사이트에서 필요한 데이터를 우클릭->검사->copy selector로 원하는 데이터 가져오기

ex)

#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.title.ellipsis
#body-content > div.newest-list > div > table > tbody > tr:nth-child(1) > td.info > a.artist.ellipsis

위의 형태로 가져온 후, 공통된 데이터를 한 변수에 저장하기

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

for 문을 돌면서 원하는 자료를 빼오기

** .text[0:2]: 원하는 텍스트 앞의 2개만 가져오기

    .strip(): 텍스트 앞뒤의 여백 제거

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()
    singer = song.select_one('td.info > a.artist.ellipsis').text.strip()
    print(rank, title, singer);

MongoDB

Python 패키지 pymongo 설치

기본 문법

from pymongo import MongoClient
client = MongoClient('mongodb+srv://내가만든아이디: 내가만든 비밀번호@ 내DB 이름.m7jzf.mongodb.net/Cluster0?retryWrites=true&w=majority')
db = client.dbsparta

기본 문법 from Sparta Coding

# 저장 - 예시
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'})

 

728x90