[TIL]221206

grace·2022년 12월 6일

TIL/WIL

목록 보기
6/37
post-thumbnail

What I Learned Today

파이썬 strip() 함수 - 문자열 및 공백제거**

//공백을 제거하는 경우
string = "    hello      "
string.strip()
//hello

//문자열을 제거하는 경우
string = "    hello      "
string.strip('o')
//hell

웹스크래핑 연습하기!

(1) 영화제목 '가버나움'의 평점을 가져오기

target_movie = db.movies.find_one({'title':'가버나움'})
print(target_movie['star'])

(2) '가버나움'의 평점과 같은 평점의 영화 제목들을 가져오기

아직까지는 조금 어려웠다!

1.
target_movie = db.movies.find_one({'title':'가버나움'})
print(target_movie['star']) 
//여기에서 print 부분을 지워준다.

2.
target_movie = db.movies.find_one({'title':'가버나움'})
star = movie['star']
// 평점을 가져오고...

3.
target_movie = db.movies.find_one({'title':'가버나움'})
star = movie['star']

all_movies = list(db.users.find({'star':star},{'_id':False}))
for m in all_movies:
	print(m['title'])
//제목만 가져와야하니까 print title 만 해준다.

(3) '가버나움' 영화의 평점을 0으로 만들기

db.movies.update_one({'title':'가버나움'},{'$set':{'star':'0'}})

Key Concepts

#웹스크래핑(크롤링) :웹 페이지를 그대로 가져와서 거기서 데이터를 추출해 내는 행위다. 웹스크래핑


Code Snippets

Q. 지니뮤직의 1~50위 곡을 스크래핑 해보세요.
순위 / 곡 제목 / 가수를 스크래핑 하면 됩니다.

💡 힌트:
0) 출력 할 때는 print(rank, title, artist) 하면 됩니다!
1) 앞에서 두 글자만 끊기! text[0:2] 를 써보세요!
2) 순위와 곡제목이 깔끔하게 나오지 않을 거예요. 옆에 여백이 있다던가, 다른 글씨도 나온다던가.. 파이썬 내장 함수인 strip()을 잘 연구해보세요!

//기본세팅 

from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:sparta@cluster0.spyade6.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')

//코드는 이 아래 부터! 

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

rank

for tr in trs:
  rank = tr.select_one('td.number').text[0:2].strip()
	//.text[0:2] 0부터 2자리까지 끊어주고 strip()으로 공백제거 

title

for tr in trs:
	title = tr.select_one('td.info > a.title.ellipsis').text.strip()
//text 만 남기고 strip() 으로 공백제거

artist

for tr in trs:
	artist = tr.select_one('td.info > a.artist.ellipsis').text
//text 만 남기기

완성

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

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)


Challenges Experienced

강의 1회독 할때는 쉽다고 생각하며 따라하기만 했는데 안보고 혼자 공부하려니 하나도 못 하겠다.
내일까지 2회독 완강해야하는데 한숨나온다...내일은 일찍 일어나서 빡코!!!!

profile
미래의 개발자!

0개의 댓글