해결된 질문
작성
·
245
0
import openpyxl
import requests
from bs4 import BeautifulSoup
# stock_data파일을 불러와서 B2, B3, B4에 현재가를 저장해보자.
fpath = (
r"C:\Users\UserName\OneDrive\바탕 화면\웹 스크래핑 연습\new_project\02_파이썬엑셀다루기\stock_data.xlsx"
)
wb = openpyxl.load_workbook(fpath)
ws = wb.active # 현재 활성화된 엑셀시트를 선택한다
# ws = wb["주식크롤링"]
def stock_crawl(codes):
row_start = 2
for code in codes:
url = f"https://finance.naver.com/item/sise.naver?code={codes[code]}"
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, "html.parser")
price = soup.select_one("#_nowVal").text
# str -> int
price = int(price.replace(",", ""))
# 크롤링한 현재가를 엑셀에 저장(3번 반복)
ws[f"B{row_start}"] = price
row_start += 1
# 엑셀 저장하기
wb.save(fpath)
stock_crawl({"엔씨소프트": "036570", "삼성전자": "005930", "네이버": "035420"})
크롤링 재밌네요 ㅎㅎ