3-3. 크롤링한 데이터를 json 파일 만들기
2018. 6. 10. 18:50ㆍCoding/Python
728x90
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import requests from bs4 import BeautifulSoup as BS import csv import json def mnet_Crawling(html): temp_list = [] temp_dict = {} tr_list = html.select('div.MnetMusicList.MnetMusicListChart > div.MMLTable.jQMMLTable > table > tbody > tr') for tr in tr_list : rank = int(tr.find('td',{'class':'MMLItemRank'}).find('span').text.strip('위')) img = tr.find('td',{'class':'MMLItemTitle'}).find('div',{'class':'MMLITitle_Album'}).find('img')['src'] img = tr.find('td',{'class':'MMLItemTitle'}).find('div',{'class':'MMLITitle_Album'}).find('img').get('src') title = tr.find('td',{'class':'MMLItemTitle'}).find('div',{'class':'MMLITitle_Box info'}).find('a',{'class':'MMLI_Song'}).text artist = tr.find('td',{'class':'MMLItemTitle'}).find('div',{'class':'MMLITitle_Box info'}).find('a',{'class':'MMLIInfo_Artist'}).text album = tr.find('td',{'class':'MMLItemTitle'}).find('div',{'class':'MMLITitle_Box info'}).find('a',{'class':'MMLIInfo_Album'}).text temp_list.append([rank, img, title, artist, album]) temp_dict[str(rank)] = {'img':img, 'title':title, 'artist':artist, 'album':album} return temp_list, temp_dict #============================================================ End of mnet_Crawling() ============================================================# def toCSV(mnet_list): with open('mnet_chart.csv', 'w', encoding='utf-8', newline='') as file : csvfile = csv.writer(file) for row in mnet_list: csvfile.writerow(row) #============================================================ End of toCSV() ============================================================# def toJson(mnet_dict): with open('mnet_chart.json', 'w', encoding='utf-8') as file : json.dump(mnet_dict, file, ensure_ascii=False, indent='\t') #============================================================ End of toCSV() ============================================================# mnet_list = [] mnet_dict = {} req = requests.get('http://www.mnet.com/chart/TOP100/') for page in [1,2]: req = requests.get('http://www.mnet.com/chart/TOP100/?pNum={}'.format(page)) html = BS(req.text, 'html.parser') mnet_temp = mnet_Crawling(html) mnet_list += mnet_temp[0] mnet_dict = dict(mnet_dict, **mnet_temp[1]) # 리스트 출력 for item in mnet_list : print(item) # 사전형 출력 for item in mnet_dict : print(item, mnet_dict[item]['img'], mnet_dict[item]['title'], mnet_dict[item]['artist'], mnet_dict[item]['album']) # CSV파일 생성 toCSV(mnet_list) # Json파일 생성 toJson(mnet_dict) | cs |
CSV때와 마찬가지로, Json모듈을 이용하면 간단합니다.
1. Json 모듈 import
import json
2. toJson()함수 생성
# Json파일 생성
toJson(mnet_dict)
def toJson(mnet_dict):
with open('mnet_chart.json', 'w', encoding='utf-8') as file :
json.dump(mnet_dict, file, ensure_ascii=False, indent='\t')
csv때와 마찬가지로 아래와같은 에러가 나타나면
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)
encoding = 'utf-8'을 넣어주면 됩니다.
indent = '\t'는 위의 결과물 mnet_chart.json과 같이 들여쓰기를 해주는 역할을 합니다.
안해도 상관없지만, 데이터를 직접볼떄 유용합니다.
728x90
'Coding > Python' 카테고리의 다른 글
요일 구하기 (0) | 2018.11.03 |
---|---|
[Python]Atom에디터 UnicodeEncodeError: 'cp949' codec can't encode character (0) | 2018.08.10 |
3-2. 크롤링한 데이터를 csv 파일 만들기 (0) | 2018.06.10 |
3-1. 크롤링한 데이터를 리스트화 List [], 사전화 Dict {} (3) | 2018.05.27 |
2-4. BeautifulSoup를 이용한 Mnet 차트 크롤링 하기[함수] (0) | 2018.05.26 |