본문 바로가기

Backend/Python

웹크롤링 2.주식현재가 엑셀로 저장하기

1. 네이버에서 주식 현재가 수집하기

import requests
from bs4 import BeautifulSoup

codes = [
    '005930', #삼성전자
    '263750', #펄어비스
    '035720' #카카오
]

for code in codes:
    url = f"https://finance.naver.com/item/sise.naver?code={code}"
    response = requests.get(url)
    html = response.text
    soup = BeautifulSoup(html, 'html.parser')
    price = soup.select_one("#_nowVal").text
    price = price.replace(',', '')
    print(price)

2. 엑셀 만들기

import openpyxl

wb = openpyxl.Workbook()

ws = wb.active

ws['A1'] = '종목'
ws['B1'] = '현재가'

ws['A2'] = '삼성전자'
ws['A3'] = '펄어비스'
ws['A4'] = '카카오'

wb.save(r'C:\startcoding\chapter04\data.xlsx')

3. 엑셀 불러오기

import requests
from bs4 import BeautifulSoup
import openpyxl

fpath = r'C:\startcoding\chapter04\data.xlsx'
wb = openpyxl.load_workbook(fpath)
ws = wb.active

codes = [
    '005930',
    '263750',
    '035720'
]

row = 2
for code in codes:
    url = f"https://finance.naver.com/item/sise.naver?code={code}"
    response = requests.get(url)
    html = response.text
    soup = BeautifulSoup(html, 'html.parser')
    price = soup.select_one("#_nowVal").text
    price = price.replace(',', '')
    print(price)
    ws[f'B{row}'] = int(price)
    row += 1

wb.save(fpath)

 

'Backend > Python' 카테고리의 다른 글

첫코딩 : 배스킨라빈스31 게임  (0) 2022.03.17
웹크롤링 3. 셀레니움으로 네이버 상품정보 수집  (0) 2022.03.02
웹크롤링 1. 뉴스제목+링크 가져오기  (0) 2022.03.02
모듈  (0) 2022.02.06
예외처리  (0) 2022.02.06