
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
강사님께서 말씀하신 대로 ChatGPT에 "네이버 금융 사이트에서 삼성전자 재무제표를 크롤링해서 데이터프레임으로 보여주는 Python 코드를 작성해줘." 라고 작성하고 결과값으로 얻은 코드를 Colab에 넣었더니 오류가 뜨더라구요. 그런데 강사님 화면에 있는 결과 값을 그대로 넣으면 제대로 재무제표 표가 불러와졌어요. ChatGPT 가 생성한 코드에는 오류가 있어서 그런걸까요? 계속 같은 질문을 했더니 다른 코드를 주긴 하는데, 해당 코드들도 전부다 제대로 결과를 주진 않네요.
작성한 코드 및 에러 메세지
import requests
from bs4 import BeautifulSoup
import pandas as pd
def get_samsung_finance():
url = 'https://finance.naver.com/item/main.nhn?code=005930' # 삼성전자 종목코드
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
} # User-Agent를 헤더에 추가하여 봇으로 인식되지 않도록 함
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 연간 재무제표 테이블 추출
table = soup.find('table', {'class': 'tb_type1 tb_num tb_type1_ifrs'})
rows = table.find_all('tr')
# 테이블 데이터를 추출하여 데이터프레임으로 변환
data = []
for row in rows:
cols = row.find_all('td')
cols = [col.text.strip() for col in cols]
data.append(cols)
# 첫 번째 row가 컬럼명, 두 번째 row가 실제 데이터
columns = data[0]
data = data[1:]
# 데이터프레임 생성
df = pd.DataFrame(data, columns=columns)
return df
# 삼성전자 재무제표 데이터프레임 출력
samsung_df = get_samsung_finance()
print(samsung_df)
발생 시, 작성한 코드 전체와 에러 메시지를 첨부해 주세요.
AssertionError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/internals/construction.py in _finalize_columns_and_data(content, columns, dtype)
933 try:
--> 934 columns = _validate_or_indexify_columns(contents, columns)
935 except AssertionError as err:
6 frames
AssertionError: 0 columns passed, passed data had 10 columns
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/internals/construction.py in _finalize_columns_and_data(content, columns, dtype)
935 except AssertionError as err:
936 # GH#26429 do not raise user-facing AssertionError
--> 937 raise ValueError(err) from err
938
939 if len(contents) and contents[0].dtype == np.object_:
ValueError: 0 columns passed, passed data had 10 columnsTip 1) </> 아이콘을 눌러 코드박스를 만들어 보세요.
Tip 2) Ctrl+A(맥의 경우 Command+A) 단축키로 코드를 한 번에 선택할 수 있어요!
