Big Data , ML/ETL, ELT

증권사 추천종목 크롤링

Dev.BeryL 2022. 2. 1. 19:37
728x90

사이트 : https://money2.daishin.com/E5/ResearchCenter/Work/DW_Research_PromList.aspx?pr_code=5&itemgroup=1&m=966&p=1062&v=2297

 

Monthly > 유망종목 - 대신증권

 

money2.daishin.com

 

페이지에서 가져올 데이터를 선정한다.

F12 또는 Ctrl+Shift+I 키를 눌러 개발자 도구를 열고 inspector를 클릭하고 수집을 원하는 문구를 클릭한다.

 

수집하려는 단위 항목의 범위를 확인하고 특징이 있는 tag 및 class 명칭 등을 확인한다.

마우스를 HTML tag 하나 하나 올리면서 이동하면서 확인하면 각 tag 별로 범위를 확인할 수 있다.

위와 같은 방법으로 확인한 우리가 수집하려는 데이터 구조는 다음과 같다. (주황색 항목)

  • div PortListArea1
    • ul portList (반복 row 4개)
      • li → div inner (반복 column 3개)
        • div titBox
          • div tit
            • em
          • span icon
            • img attr[alt]
        • div detail
          • div detailChart
            • dd[1]
            • dd[2]
            • p date
import requests
from bs4 import BeautifulSoup

def main():
  url = '' # 맨위 사이트 URL 입력
  res = requests.get(url)
  html = res.text
  soup = BeautifulSoup(html, 'html.parser')
  portListArea = soup.find('div', 'portListArea1')
  portLists = portListArea.find_all('ul', 'portList')
  print(portLists)

if __name__ == '__main__':
  main()

위 코드를 실행해서 정상적인 출력이 되면 loop를 돌면서 각 항목을 수집한다.

tag명 class명 등을 활용해서 항목을 find 한다.

 

for i in range(0, len(portLists)): # row 반복
  portListLis = portLists[i].find_all('li')
  for j in range(0, len(portListLis)): # column 반복
    tit = portListLis[j].find('h4', 'tit')
    if tit == None:
      break

    name = tit.get_text()
    names = name.split('(')
    name = names[0]
    code = names[1].replace(')', '')
    icon = portListLis[j].find('span', 'icon').find('img')
    market = icon.attrs['src']
    if market == None or market == '':
      break

    market = icon.attrs['alt']
    detail = portListLis[j].find('div', 'detailChart')
    dd = detail.find_all('dd')
    for k in range(0, len(dd)): # 0:수익률, 1:현재가, 2:전일종가
      if k == 1:
        current_price = dd[k].string.replace(',', '')
      elif k == 2:
        start_price = dd[k].string.replace(',', '')
    start_date = detail.find('p', 'date').string.replace('추천일 ', '').replace('.', '-')
    print(code+'\t'+name+'\t'+market+'\t'+start_price+'\t'+current_price+'\t'+start_date)

 

.find(태그, 클래스...) : 태그가 맞는 항목 1개 찾기

.find_all(태그, 클래스...) : 태그와 클래그가 맞는 항목 모두 찾기, 배열로 처리됨

.get_text() : 하위 모든 tag를 없애고 문자열만 추출

.string : 하위 문자열 추출, 하위 tag가 있으면 None

.attrs[속성명] : 현재 tag의 속성(attribute) 값, <tag명 속성="값">text</tag>

반응형