커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
삼성전자 제무제표 불러오기 코드를 chatgpt 4로 작성해서 colab에 붙여넣고 실행하니까 에러뜨고 실행이 안됩니다. 에러 고려해서 다시 짜라고 요구해도 잘 안되요..
undefined주차
북마크
김*수
댓글
3
추천
0
조회수
16
조회수
16
답변 완료
1번 시도
import requests
from bs4 import BeautifulSoup
import pandas as pd


# 삼성전자 연간 재무제표 페이지 URL
url = 'https://finance.naver.com/item/main.nhn?code=005930&target=finsum_more'


# 페이지 데이터 가져오기
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')


# 재무제표 테이블 선택
table = soup.select('div.section.cop_analysis div.sub_section')[0]


# 테이블 헤더 가져오기
header_data = [item.get_text().strip() for item in table.select('thead th')]


# 테이블 바디 가져오기
body_data = [item.get_text().strip() for item in table.select('tbody td')]


# 헤더와 바디 데이터를 DataFrame으로 변환
n_cols = len(header_data)
n_rows = int(len(body_data) / n_cols)


header = pd.Series(header_data).values.reshape(-1, 1).T
body = pd.Series(body_data).values.reshape(-1, n_cols)


df = pd.DataFrame(
    data = pd.concat([pd.DataFrame(header), pd.DataFrame(body)]),
    columns = [f"col_{i}" for i in range(n_cols)]
)


print(df)

1번 에러
//
ValueError                                Traceback (most recent call last)
<ipython-input-11-ad58765dbd7f> in <cell line: 26>()
     24 
     25 header = pd.Series(header_data).values.reshape(-1, 1).T
---> 26 body = pd.Series(body_data).values.reshape(-1, n_cols)
     27 
     28 df = pd.DataFrame(

ValueError: cannot reshape array of size 160 into shape (23)

2번 시도
//
import requests
from bs4 import BeautifulSoup
import pandas as pd


# 삼성전자 연간 재무제표 페이지 URL
url = 'https://finance.naver.com/item/main.nhn?code=005930&target=finsum_more'


# 페이지 데이터 가져오기
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')


# 재무제표 테이블 선택
table = soup.select('div.section.cop_analysis div.sub_section')[0]


# 테이블 헤더 가져오기
header_data = [item.get_text().strip() for item in table.select('thead th')]


# 테이블 바디의 각 행 가져오기
rows = table.select('tbody tr')


body_data = []
for row in rows:
    cols = row.select('td')
    cols = [ele.text.strip() for ele in cols]
    body_data.append([ele for ele in cols if ele]) # Get rid of empty values


df = pd.DataFrame(body_data, columns=header_data)


print(df)

2번 에러
//
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)
    968     try:
--> 969         columns = _validate_or_indexify_columns(contents, columns)
    970     except AssertionError as err:


5 frames
AssertionError: 23 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)
    970     except AssertionError as err:
    971         # GH#26429 do not raise user-facing AssertionError
--> 972         raise ValueError(err) from err
    973 
    974     if len(contents) and contents[0].dtype == np.object_:

ValueError: 23 columns passed, passed data had 10 columns

3번 시도
//
from bs4 import BeautifulSoup
from selenium import webdriver
import pandas as pd
import time


# ChromeDriver 경로 설정
driver_path = '/path/to/chromedriver'


# WebDriver 객체 생성
driver = webdriver.Chrome(driver_path)


# 삼성전자 연간 재무제표 페이지로 이동
url = 'https://finance.naver.com/item/main.nhn?code=005930&target=finsum_more'
driver.get(url)


# 페이지 로딩 대기
time.sleep(3)


# 페이지 소스 가져오기
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')


# 재무제표 테이블 선택
tables = soup.select('div.section.cop_analysis div.sub_section')


# 각 테이블을 별도의 DataFrame으로 저장
dfs = []


for table in tables:
    # 테이블 헤더 가져오기
    header_data = [item.get_text().strip() for item in table.select('thead th')]


    # 테이블 바디의 각 행 가져오기
    rows = table.select('tbody tr')
    body_data = []
    for row in rows:
        cols = row.select('td')
        cols = [ele.text.strip() for ele in cols]
        body_data.append([ele for ele in cols if ele])  # Get rid of empty values


    df = pd.DataFrame(body_data, columns=header_data)
    dfs.append(df)


# WebDriver 종료
driver.quit()


# DataFrame 출력
for df in dfs:
    print(df)
    print("\n---\n")

3번 에러
//
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-13-a24c722ff0f8> in <cell line: 2>()
      1 from bs4 import BeautifulSoup
----> 2 from selenium import webdriver
      3 import pandas as pd
      4 import time
      5 

ModuleNotFoundError: No module named 'selenium'
---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.




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

chatgpt4한테 에러 고려해서 다시 코드를 작성하라고 했습니다.

이걸 chatgpt를 이용하여 해결할 수 있나요?

문제가 있었다면 어떤점이 문제였나요?(똑같은 상황방지)









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