
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
재무제표 크롤링 하려고 지피티한테 물어보고 긁어왔는데
아래처럼 오류가 났어요 어떤 문제인지 감을 잡을 수가 없어서 질문드립니다.
import requests
from bs4 import BeautifulSoup
import pandas as pd
def get_financial_statements(stock_code):
url = f"https://finance.naver.com/item/main.nhn?code={stock_code}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 재무제표 탭의 URL을 가져오기
fs_url = soup.find("a", {"href": "#p11"}).get('href')
fs_response = requests.get("https://finance.naver.com" + fs_url, headers=headers)
fs_soup = BeautifulSoup(fs_response.text, 'html.parser')
# 재무제표 데이터를 담을 딕셔너리 생성
financial_statements = {}
# 테이블에서 데이터 추출
for table in fs_soup.find_all('table'):
# 각 테이블의 제목 추출
title = table.find_previous_sibling('h4')
if title:
title = title.text
else:
continue
# 데이터 추출하여 딕셔너리에 추가
data = []
for row in table.find_all('tr'):
row_data = [cell.text.strip() for cell in row.find_all(['th', 'td'])]
data.append(row_data)
financial_statements[title] = data
return financial_statements
# 삼성전자의 재무제표 크롤링
samsung_financial_statements = get_financial_statements("005930")
# 데이터프레임으로 변환하여 출력
for title, data in samsung_financial_statements.items():
df = pd.DataFrame(data[1:], columns=data[0])
print("\n", title)
print(df)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-612f900d61e1> in <cell line: 39>()
37
38 # 삼성전자의 재무제표 크롤링
---> 39 samsung_financial_statements = get_financial_statements("005930")
40
41 # 데이터프레임으로 변환하여 출력
<ipython-input-4-612f900d61e1> in get_financial_statements(stock_code)
11
12 # 재무제표 탭의 URL을 가져오기
---> 13 fs_url = soup.find("a", {"href": "#p11"}).get('href')
14 fs_response = requests.get("https://finance.naver.com" + fs_url, headers=headers)
15 fs_soup = BeautifulSoup(fs_response.text, 'html.parser')
AttributeError: 'NoneType' object has no attribute 'get'
