네이버 금융 페이지 중 시가총액 순위 페이지에서 데이터를 가져와 엑셀과 CSV로 저장
Power Automate Desktop 버전은 아래 링크에서 확인할 수 있습니다.
https://ggondae.tistory.com/99
[Power Automate Desktop] 기업 시가총액 순위, 엑셀 저장 (Detail Version)
심플버전에서는 웹 페이지의 표를 전체 HTML테이블 추출을 통해 한번에 가져와 엑셀로 저장하였습니다. 그러다보니 엑셀이 완전한 형태로 만들어지지 않게 되었고 다음 작업을 자동화로 만들기
ggondae.tistory.com
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
import csv
HEADERS = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/90.0.4430.93 Safari/537.36',
'Accept-Language':'ko-KR,ko',
}
# 한 페이지에 50위까지 나오며 그 이상은 page수를 늘린다.
URL = 'https://finance.naver.com/sise/sise_market_sum.nhn?sosok=0&page='
# 엑셀 파일 생성
wb = Workbook()
ws = wb.active
# CSV로 저장
filename = 'finance_csv.csv'
f = open(filename, 'w', encoding='utf-8-sig', newline='')
w = csv.writer(f)
# 시가총액 100위까지
for idx in range(1, 2):
res = requests.get(URL+str(idx), headers=HEADERS)
res.raise_for_status()
soup = BeautifulSoup(res.text, 'lxml')
# 타이틀 처리
# 웹페이지를 복사해서 처리할 경우, 문자열을 \t으로 나눠 리스트로 저장
# title = 'N 종목명 현재가 전일비 등락률 액면가 시가총액 상장주식수 외국인비율 거래량 PER ROE'.split('\t')
# 읽어서 처리할 경우
if(idx == 1):
cols = soup.find('table', attrs={'class':'type_2'}).find('thead').find('tr').find_all('th')
title = []
for ii, col in enumerate(cols):
if ii == 0:
title.append('순위')
continue
if ii == len(cols)-1:
continue
title.append(col.get_text().strip())
# 엑셀 저장
ws.append(title)
# CSV 저장
w.writerow(title)
# 시가총액 순위 데이터
rows = soup.find('table', attrs={'class':'type_2'}).find('tbody').find_all('tr')
for row in rows:
cols = row.find_all('td')
# 줄 바꿈을 위해 있는 tr은 td가 하나 이하이므로 skip한다.
if len(cols) <= 1:
continue
data = []
# 맨 끝 '토론실' 컬럼은 제외한다.
for ii, col in enumerate(cols):
if ii == len(cols)-1:
continue
# 문자열 내 공백 제거
data.append(col.get_text().strip())
# 엑셀 저장
ws.append(data)
# CSV 저장
w.writerow(data)
# 엑셀 파일 저장
wb.save('finance_excel.xlsx')
'RPA > Python' 카테고리의 다른 글
[Pandas] 기업 시가총액 순위, 엑셀 저장 (0) | 2022.02.02 |
---|---|
[BeautifulSoup, selenium] 동적 스크롤 페이지 스크래핑 (0) | 2021.05.14 |
[BeautifulSoup] 웹 스크래핑 (WEB Scraping) 환경 설정 및 기초 (0) | 2021.05.12 |
[openpyxl, python-pptx] 엑셀 주소록 읽어 파워포인트로 명찰 만들기 (0) | 2021.05.09 |
[python-pptx] 특정 슬라이드를 하나의 파일로 만들기 (0) | 2021.05.09 |