커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
네이버 금융 사이트에서 삼성전자 재무제표를 크롤링해서 데이터프레임으로 보여주는 Python 코드를 작성해줘 프롬프트로 생성된 코드 실행 오
[왕초보] ChatGPT 300% 활용하기 v0
1주차
북마크
이*민
댓글
3
추천
0
조회수
8
조회수
8
답변 완료

* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.

* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.


import requests

from bs4 import BeautifulSoup

import pandas as pd


# 네이버 금융 삼성전자 재무제표 URL

url = 'https://finance.naver.com/item/main.nhn?code=005930'


# HTTP GET 요청

response = requests.get(url)

response.encoding = 'euc-kr'  # 네이버 금융 페이지의 인코딩 설정


# BeautifulSoup 객체 생성

soup = BeautifulSoup(response.text, 'html.parser')


# 재무제표 정보가 담긴 테이블 선택

# "cop_analysis" ID를 가진 테이블의 헤더(header)와 바디(body) 부분을 추출

finance_html = soup.select_one('div.section.cop_analysis div.sub_section')


# 테이블 헤더 추출

th_data = [item.get_text().strip() for item in finance_html.select('thead th')]

annual_dates = th_data[3:7]  # 연간 날짜 추출

quarter_dates = th_data[7:13]  # 분기 날짜 추출


# 테이블 본문 데이터 추출

finance_index = []

finance_data = []

for item in finance_html.select('table tbody tr'):

    title = item.select_one('th').get_text().strip()

    finance_index.append(title)

    td_data = [td.get_text().strip() for td in item.select('td')]

    finance_data.append(td_data)


# 데이터 프레임 생성

finance_df_annual = pd.DataFrame(data=finance_data, index=finance_index, columns=annual_dates)

finance_df_quarter = pd.DataFrame(data=finance_data, index=finance_index, columns=quarter_dates)


# 연간 재무제표 출력

print("연간 재무제표:")

print(finance_df_annual)


# 분기 재무제표 출력

print("\n분기 재무제표:")

print(finance_df_quarter)






작성한 코드 및 에러 메세지

---------------------------------------------------------------------------
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:


5 frames

AssertionError: 4 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: 4 columns passed, passed data had 10 columns오류 발생 시, 작성한 코드 전체와 에러 메시지를 첨부해 주세요.

Tip 1) </> 아이콘을 눌러 코드박스를 만들어 보세요.

Tip 2) Ctrl+A(맥의 경우 Command+A) 단축키로 코드를 한 번에 선택할 수 있어요!




취소
 공유
취소
댓글 0
댓글 알림
나의얼굴