Group1 주요국 국채금리 그래프

packages = ["matplotlib", "pandas", "requests", "bs4", "numpy"] ####### Group1 주요국 국채금리 그래프 그리기 import requests from bs4 import BeautifulSoup import numpy as np import pandas as pd import datetime import matplotlib.pyplot as plt import random # search_word='미국 국채수익률'#여기에 검색하고 싶은 단어를 입력하세요! # search_word_group = ['미국'] #여기에 검색하고 싶은 단어를 입력하세요! search_word_group = ['한국', '미국', '유로', '영국', '일본', '중국', '독일', '프랑스', '이탈리아', '캐나다', '호주', '러시아', '브라질', '인도', '튀르키예', '남아프리카공화국', '멕시코', '인도네시아'] #여기에 검색하고 싶은 단어를 입력하세요! columns = ['gather_time', 'country', 'month', 'market_time', 'rate', 'gap', 'gap_rate', 'percent'] df = pd.DataFrame(columns=columns) for search_word in search_word_group : url= f'https://search.naver.com/search.naver?where=nexearch&sm=tab_etc&mra=blJH&qvt=0&query={search_word} 국채수익률' # url= f'https://search.naver.com/search.naver?where=nexearch&sm=tab_etc&mra=blJH&qvt=0&query=%EB%AF%B8%EA%B5%AD%20%EA%B5%AD%EC%B1%84%EC%88%98%EC%9D%B5%EB%A5%A0' req=requests.get(url) html = req.text # print (html) soup = BeautifulSoup(html, 'html.parser') # print (soup) # search_result = soup.select_one('li.info_box') # (중요)
  • 를 찾아서 맨 처음만 출력 search_result = soup.select('li.info_box') # (중요)
  • 를 찾아서 모든 것 출력 # print (search_result) now = datetime.datetime.now() # 현재 날짜와 시간 구하기 for i in search_result: # print (i) new = {'gather_time': now.strftime("%Y-%m-%d %H:%M:%S"), 'country' : i.select('strong.title')[0].text.split(' ')[0], # (겁나중요) [0].text 를 적용해야 시리즈 형식을 제거함!!!!!! 'month' : i.select('strong.title')[0].text.split(' ')[2].replace('개월', ''), # (겁나중요) [0].text 를 적용해야 시리즈 형식을 제거함!!!!!! 'market_time': i.select('span.sub_text')[0].text.replace('실시간', '').replace('현지', '').replace('2시간 지연', ''), 'rate' : i.select('span.num')[0].text, 'gap_rate' : i.select('span.gap')[0].text[:-4], # 문자열의 마지막 2자를 제외하고 부분 문자열로 추출하기 'gap' : i.select('span.gap')[0].text[-3:], # 문자열의 마지막 2자를 부분 문자열로 추출하기 'percent' : i.select('div.rof_box')[0].text.replace('등락률', '').replace('%', '').replace('+', '') } df = df.append(new, ignore_index=True) # 판다스 2.0 미만에서만 append 가능 df = df.replace({'gap_rate' : ''}, 0) # df['gap_num'] 데이터 중에서 ''인 것을 0으로 치환 # month에서 년으로 표식된 것을 월로 변경하는 코드 df.loc[df['month'].str.contains('년'),'month'] = df[df['month'].str.contains('년')]['month'].str.replace('년', '').astype('int64') * 12 df['month'] = df['month'].astype('int64') # 정렬 위해 문자형를 정수형으로 변경 df['rate'] = df['rate'].astype('float') # 그래프 생성을 위해 문자형를 정수형으로 변경 df = df.sort_values(['country','month'], ascending=True) # 나라와 개월수로 정렬 df = df.reset_index(inplace=False, drop=True) # 인덱스 재정렬 print df