프로젝트 세팅
크롤링을 하기위한 [requests, bs4]패키지 설치하기
웹스크래핑 결과 저장하기
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
import certifi
ca = certifi.where()
#test와 sparta는 개인이 mongoDB에 설정하는 영역이다.
client = MongoClient('mongodb+srv://test:sparta@cluster0.euhwlug.mongodb.net/?retryWrites=true&w=majority', tlsCAFile=ca)
db = client.dbsparta
# 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 = BeautifulSoup(data.text, 'html.parser')
# select를 이용해서, tr들을 불러오기
movies = soup.select('#old_content > table > tbody > tr')
# movies (tr들) 의 반복문을 돌리기
for movie in movies:
# movie 안에 a 가 있으면,
a_tag = movie.select_one('td.title > div > a')
if a_tag is not None:
rank = movie.select_one('td:nth-child(1) > img')['alt'] # img 태그의 alt 속성값을 가져오기
title = a_tag.text # a 태그 사이의 텍스트를 가져오기
#mongoDB에 movie라는 디렉토리를 생성함과 동시에 저장하는 명령
star = movie.select_one('td.point').text # td 태그 사이의 텍스트를 가져오기
#python 딕셔너리문법
doc = {
'rank': rank,
'title': title,
'star': star
}
db.movies.insert_one(doc)
웹스크래핑 결과 이용하기
(1) 영화제목 '가버나움'의 평점을 가져오기
target_movie = db.movies.find_one({'title':'가버나움'})
print(target_movie['star'])
(2) '가버나움'의 평점과 같은 평점의 영화 제목들을 가져오기
target_movie = db.movies.find_one({'title':'가버나움'})
target_star = target_movie['star']
movies = list(db.movies.find({'star':target_star}))
for movie in movies:
print(movie['title'])
(3) '가버나움' 영화의 평점을 0으로 만들기
db.movies.update_one({'title':'가버나움'},{'$set':{'star':'0'}})
'지니'사이트 순위 / 곡 제목 / 가수를 스크래핑 하기
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:
title = tr.select_one('td.info > a.title.ellipsis').text.strip()
rank = tr.select_one('td.number').text[0:2].strip()
artist = tr.select_one('td.info > a.artist.ellipsis').text
print(rank, title, artist)
'내일배움캠프[4기_Reac트랙] > 웹개발종합반(내일배움단)' 카테고리의 다른 글
4주차(6~9)-화성땅 공동구매(GET, POST) (0) | 2022.11.03 |
---|---|
4주차(1~5)-Flask 사용법 (0) | 2022.11.02 |
3주차(11~13)-mongoDB조작법 (0) | 2022.11.02 |
3주차(8~9)-웹스크래핑(크롤링) (0) | 2022.11.01 |
3주차(7)-패키지 사용해보기 (0) | 2022.11.01 |