1. 🌟파이썬 기초 문법

https://velog.io/@junsikchoi/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EA%B8%B0%EB%B3%B8-%EB%AC%B8%EB%B2%95-%EC%9A%94%EC%95%BD-%EC%A0%95%EB%A6%AC

 

파이썬 기본 문법 요약 정리

간단하게 파이썬 기초 문법을 정리해보자변수 (Variable)은 데이터 값의 식별자이다.id() 메서드를 통해 해당 변수의 위치를 알 수 있다. (C 언어에서의 변수의 메모리상에서의 위치라고 할 수 있다.

velog.io

2. 🌟웹크롤링 기본 세팅 (BeautifulSoup사용)

https://twpower.github.io/84-how-to-use-beautiful-soup

 

[Python] 웹 크롤링에 사용하는 Beautiful Soup(뷰티플 수프) 사용법과 예제

Practice makes perfect!

twpower.github.io

import requests
from bs4 import BeautifulSoup

# 타겟 URL을 읽어서 HTML를 받아오고,
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.naver?sel=pnt&date=20210829',headers=headers)

# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦
# soup이라는 변수에 "파싱 용이해진 html"이 담긴 상태가 됨
# 이제 코딩을 통해 필요한 부분을 추출하면 된다.
soup = BeautifulSoup(data.text, 'html.parser')

#############################
# (입맛에 맞게 코딩)
#############################

3. 🌟modgoDB 연결 및 pymongo 

from pymongo import MongoClient
client = MongoClient('내URL')
db = client.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'})

4. 🌟지니뮤직 스크래핑

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)

#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

soup = BeautifulSoup(data.text, 'html.parser')
musics = soup.select('#body-content > div.newest-list > div > table > tbody > tr')
for music in musics:
        title = music.select_one('td.info > a.title.ellipsis').text.strip()
        number = music.select_one('td.number').text[0:2].strip()
        artist = music.select_one('td.info > a.artist.ellipsis').text.strip()
        doc = {
            'title' : title,
            'number': number,
            'artist': artist
        }
        print(number, title, art)
복사했습니다!