<td class = "title"> > <div class = "tit5"> > <a>
<td class = "point">
# requirements
import pandas as pd
import urllib
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
url = "https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=cur&date=20221019"
response = urlopen(url)
# response.status -> 200 확인
soup=BeautifulSoup(response, "html.parser")
print(soup.prettify())
soup.find_all("div","tit5")
# soup.select(".tit5") 동일방법
soup.find_all("div","tit5")[0].a.string
# soup.select(".tit5")[0].find("a").text
# soup.select(".tit5")[0].select_one("a").get_text() 와 동일
--> '탑건: 매버릭'
# 영화 평점 태그
soup.find_all("td","point")
# soup.select(".point") 동일방법
len(soup.select(".point")), len(soup.find_all("div","tit5"))
--> (50, 50)
# 랭킹 1위의 평점 출력
soup.find_all("td","point")[0].text
--> '9.77'
#영화제목 리스트
end = len(soup.find_all("div","tit5"))
movie_name = []
# for n in range(0, end):
# movie_name.append(
# soup.find_all("div","tit5")[n].a.string
# )
# 위 for문 대신 아래 방식으로
movie_name = [soup.select(".tit5")[n].a.text for n in range(0, end)]
movie_name
# 영화 평점 리스트
end = len(soup.find_all("td","point"))
movie_point = [soup.find_all("td","point")[n].text for n in range(0, end)]
movie_point
url = "https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=cur&date=20221019"
date = pd.date_range("2022.07.01", periods=100, freq="d")
date
date[0].strftime("%Y-%m-%d")
--> '2022-07-01'
# 문자열 format
test_string = "Hi, I'm {name}."
test_string.format(name="J")
test_string.format(name="Daisy")
# dir(test_string)
--> "Hi, I'm Daisy."
import time
from tqdm import tqdm
movie_date = []
movie_name = []
movie_point = []
for today in tqdm(date):
url = "https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=cur&date={date}"
response = urlopen(url.format(date=today.strftime("%Y%m%d")))
soup = BeautifulSoup(response, "html.parser")
end = len(soup.find_all("td","point"))
movie_date.extend([today for n in range(0, end)])
movie_name.extend([soup.select("div.tit5")[n].find("a").get_text() for n in range(0, end)])
movie_point.extend([soup.find_all("td","point")[n].string for n in range(0, end)])
time.sleep(0.5) # 실행 속도 임의로 약간 느리게 설정
len(movie_date), len(movie_name), len(movie_point)
--> (3925, 3925, 3925)
# 데이터프레임 만들기
movie = pd.DataFrame({
"date":movie_date,
"name":movie_name,
"point":movie_point
})
movie.tail()
movie.info()
movie["point"] = movie["point"].astype(float)
movie.info()
import numpy as np
import pandas as pd
movie = pd.read_csv("../data/03. naver_movie_data.csv", index_col=0)
movie.tail()
# pivot table
movie_unique = pd.pivot_table(data=movie, index="name", aggfunc=np.sum)
movie_unique
movie_best = movie_unique.sort_values(by="point", ascending=False)
movie_best.head()
tmp = movie.query("name == ['탑건: 매버릭']")
tmp
import matplotlib.pyplot as plt
from matplotlib import rc
rc("font", family="Malgun Gothic")
%matplotlib inline
plt.figure(figsize=(20, 8)) # x=20, y = 8
plt.plot(tmp["date"], tmp["point"]) #선 그래프 x축 날짜, y축 평점 -->날짜에 따른 평점 변화를 선그래프로 표현
plt.title("날짜별 평점")
plt.xlabel("날짜")
plt.ylabel("평점")
plt.xticks(rotation="vertical") #날짜 세로로 표시해서 겹치지 않게 표현
plt.legend(labels=["평점추이"], loc="best")
plt.grid(True)
plt.show()
movie_best.head(10)
movie_pivot = pd.pivot_table(data=movie, index="date", columns="name", values="point")
movie_pivot.head()
엑셀 파일로 저장 후 확인
movie_pivot.to_excel("../data/03. movie_pivot.xlsx")
import platform
import seaborn as sns
from matplotlib import font_manager, rc
path = "C:/Windows/Fonts/malgun.ttf"
if platform.system() == "Darwin":
rc("font", family="Arial Unicode MS")
elif platform.system() == "Windows":
font_name = font_manager.FontProperties(fname=path).get_name()
rc("font", family=font_name)
else:
print("Unknown system. sorry")
target_col = ["탑건: 매버릭", "중경삼림","범죄도시2","엘비스","헤어질 결심"]
plt.figure(figsize=(20,8))
plt.title("날짜별 평점")
plt.xlabel("날짜")
plt.ylabel("평점")
plt.plot(movie_pivot[target_col])
plt.xticks(rotation="vertical")
plt.legend(target_col, loc="best")
plt.grid(True)
plt.show()