INVESTAR / StockAnalysisInPython

456 stars 413 forks source link

4.4.4 전체페이지 읽어오기 질문드려요 #101

Open Kimtaelim opened 3 years ago

Kimtaelim commented 3 years ago

import pandas as pd from bs4 import BeautifulSoup from urllib.request import Request, urlopen

url = "http://finance.naver.com/item/sise_day.nhn?code=068270" req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

with urlopen(req) as doc: html = BeautifulSoup(doc, 'lxml') pgrr = html.find('td', class_='pgRR') s = str(pgrr.a['href']).split('=')

스플릿함수로 분리해 3개 문자열을 리스트를 얻음

# s는 ['/item/sise_day.nhn?code', '068270&page', '351']
last_page = s[-1]  # 젠체 페이지수 구하기

print(last_page)

전체페이지 읽어오기

df = pd.DataFrame() # 데이터프레임형임을 인터프리터에 알려줌 sise_url = 'https://finance.naver.com/item/sise_day.nhn?code=068270'

for page in range(1, int(last_page)+1): # 1~마지막페이지까지 반복 page_url = '{}&page={}'.format(sise_url, page) # for문의 페이지숫자를 이용하여 url페이지수 변경 df = df.append(pd.read_html(page_url, header=0)[0]) # 한페이지분량을 df에 추가

df = df.dropna() # 값이 빠진 행을 제거 print(df)

bandicam 2021-08-06 18-06-49-879


답변 된것들 참고해서 수정을 어느정도 해봤는데 last_page 출력은 되는데 전체페이지 불러오기 부분에서 걸리는데 이유를 모르겠습니다..

코드 올려주신거로 request변경 해봐도 오류 뿐이라..

INVESTAR commented 3 years ago

마지막 페이지 숫자를 urllib.request의 Request 객체를 사용해서 구하셨네요. 개인적으로는 urllib 보다는 requests가 훨씬 더 훌륭한 라이브러리라고 생각하기 때문에 requests 라이브러리를 사용해 보실 것을 추천드립니다.

from bs4 import BeautifulSoup
import requests
import pandas as pd

url = 'https://finance.naver.com/item/sise_day.nhn?code=068270&page=1'
html = requests.get(url, headers={'User-agent': 'Mozilla/5.0'}).text
bs = BeautifulSoup(html, 'lxml')  # ①
pgrr = bs.find('td', class_='pgRR')  # ②
print(pgrr.a['href'])  # ③
/item/sise_day.nhn?code=068270&page=398

전체 일별시세를 구하지 못한 이유는 read_html()로 직접 웹 페이지를 요청할 때 브라우저 정보가 포함되어 있지 않기 때문입니다. 전체 일별시세를 구할 때에도 마찬가지로 requests로 브라우저 정보를 포함해서 각각의 웹 페이지를 요청하신 후 read_html()로 읽어야 합니다.

s = str(pgrr.a['href']).split('=')  # ④ 
last_page = s[-1]  # ⑤

df = pd.DataFrame() # ①  
sise_url = 'https://finance.naver.com/item/sise_day.nhn?code=068270'

for page in range(1, int(last_page)+1):  # ② 
    page_url = '{}&page={}'.format(sise_url, page)  # ③
    page_txt = requests.get(page_url, headers={'User-agent': 'Mozilla/5.0'}).text
    df = df.append(pd.read_html(page_txt, header=0)[0]) # ④

df = df.dropna() # ⑤ 
print(df)
            날짜        종가      전일비        시가        고가        저가       거래량
1   2021.08.06  271500.0   2500.0  271000.0  273000.0  267500.0  328096.0
2   2021.08.05  269000.0    500.0  270000.0  275000.0  268500.0  411854.0
3   2021.08.04  269500.0   4500.0  265000.0  272500.0  264500.0  497787.0
4   2021.08.03  265000.0   1500.0  263500.0  265000.0  260500.0  279936.0
5   2021.08.02  263500.0  10000.0  255500.0  264000.0  255500.0  459181.0
..         ...       ...      ...       ...       ...       ...       ...
12  2005.07.25    5650.0     70.0    5500.0    5950.0    5500.0   61036.0
13  2005.07.22    5580.0    160.0    5850.0    5850.0    5530.0   69921.0
1   2005.07.21    5740.0    810.0    6450.0    6580.0    5730.0  182685.0
2   2005.07.20    6550.0   1150.0    7690.0    7690.0    6550.0  422688.0
3   2005.07.19    7700.0   2500.0    6700.0    7700.0    6510.0  499088.0

[3973 rows x 7 columns]
INVESTAR commented 3 years ago

2021년 8월 8일 현재 시중에 나와있는 '파이썬 증권 분석' 4쇄까지는 브라우저 정보를 추가하는 코드가 반영되어 있지 않습니다. 수정된 코드는 다음 인쇄(5쇄)부터 반영되도록 교정 작업을 진행하고 있습니다.