import requests
from bs4 import BeautifulSoup as bs
import openpyxl
kp= r'C:\Users\admin\Documents\Python\Cognistocks\data\Cognistocks_data.xlsx'
wb= openpyxl.load_workbook(kp)
ws= wb.active
response_1 = requests.get("https://finance.naver.com/sise/sise_market_sum.naver")
html =response_1.text
soup= bs(html, 'lxml')
ws['A1'] = '주식 종목'
ws['B1'] = '현재가'
ws['C1'] = '전일비'
ws['D1'] = '등락률'
ws['E1'] = '액면가'
row=2
stockContents = soup.select("#contentarea > div.box_type_l > table.type_2 > tbody > tr")
for stockContent in stockContents:
try:
stockname = stockContent.select_one("td:nth-child(2)").text.strip()
stockprice = stockContent.select_one("td:nth-child(3)").text.strip()
stockrate = stockContent.select_one("td:nth-child(4)").text.strip()
stockdown = stockContent.select_one("td:nth-child(5)").text.strip()
stockac = stockContent.select_one("td:nth-child(6)").text.strip()
except AttributeError:
continue
print(f'{stockname}, {stockprice}, {stockrate}, {stockdown}, {stockac}')
ws[f'A{row}'] = stockname
ws[f'B{row}'] = stockprice
ws[f'C{row}'] = stockrate
ws[f'D{row}'] = stockdown
ws[f'E{row}'] = stockac
row = row + 1
wb.save(kp)