내일을 위한 오늘

파이썬#1. 파이썬으로 웹페이지 크롤링 스크래핑 파싱 예제 본문

IT·컴퓨터

파이썬#1. 파이썬으로 웹페이지 크롤링 스크래핑 파싱 예제

안경쓴루피 2022. 5. 29. 18:42
반응형

1. 코드 소개

 

파이썬으로 특정 웹페이지의 내용을 가져오는 소스를 만들어보았습니다.

윈도우에서 Visual Studio Code 로 코딩했으며, 크롬드라이버를 이용한 코드입니다. 

 

Visual Studio Code 설치와 파이썬 extension 설치에 관한 글은 구글에 많이 있으니 검색해 보시면 되겠습니다~

 

저는 다음 금융에서 제공하는 페이지에서 원하는 내용을 가져오는 코딩을 작성해 보았습니다.

아래 이미지에서와 같이..

외국인 + 순매수 상위 30개 종목의 종목명, 금액, 수량,등락률을 가져오도록 한 코드입니다. 

 

 

 

2. 대상 사이트

 

https://finance.daum.net/domestic/influential_investors

 

외국인/기관매매 | 다음 금융

외국인/기관매매 코스피 코스닥 -차트슬라이드

finance.daum.net

 

 

 

3. 크롤링 대상 참고 이미지

 

 

4. 파이썬 코드

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time
import random

chrome_options = Options()
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])   
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko")
#driver = webdriver.Chrome('./chromedriver.exe', options=chrome_options)


def get_data():

    # 외국인/기관매매 - 코스피 - 외국인 당일 순매수 종목
    url = 'https://finance.daum.net/domestic/influential_investors'
    driver.get(url)

    res = driver.page_source
    soup = BeautifulSoup(res,"html.parser")

    ino = 1
    while ino <= 30:

        try:
            sName = '#boxInfluentialInvestors > div.box_contents > div:nth-child(1) > table > tbody > tr:nth-child('+str(ino)+') > td:nth-child(1) > a'
            # getName = soup.select_one(sName).text
            getName = soup.select(sName)[0].text

            sAmount = '#boxInfluentialInvestors > div.box_contents > div:nth-child(1) > table > tbody > tr:nth-child('+str(ino)+') > td:nth-child(2) > span'
            getAmount = soup.select_one(sAmount).text

            sCount = '#boxInfluentialInvestors > div.box_contents > div:nth-child(1) > table > tbody > tr:nth-child('+str(ino)+') > td:nth-child(3) > span'
            getCount = soup.select_one(sCount).text

            sRate = '#boxInfluentialInvestors > div.box_contents > div:nth-child(1) > table > tbody > tr:nth-child('+str(ino)+') > td:nth-child(4) > span'
            getRate = soup.select_one(sRate).text

            #print('['+str(ino)+'] 종목명 : '+ getName + ' / 금액 : '+ getAmount +'(백만원) / 수량 : '+ getCount +'(천주) / 등락률 : '+ getRate)
            print('['+str(ino)+'] ['+ getName + '] / '+ getAmount +'(백만원) / '+ getCount +'(천주) / '+ getRate)

        except:
            #pass
            print('['+str(ino)+'] err')

        ino += 1

        #sleep_sec = random.randrange(1, 3)
        #time.sleep(sleep_sec)        


# 실행
if __name__=='__main__':

    # 시간
    now = time.localtime()
    date_ymd_his = "%02d-%02d-%02d %02d:%02d:%02d" % (now.tm_year, now.tm_mon, now.tm_mday,now.tm_hour, now.tm_min, now.tm_sec)
    print('- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ')
    print("["+ date_ymd_his +"]")
    print('- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ')


    start_time = time.time()

    driver = webdriver.Chrome('./chromedriver.exe', options=chrome_options)
    
    # 크롤링 함수 실행
    get_data()

    # driver 닫기
    driver.quit()

    # 실행 시간
    print('- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ')
    print("[Total] --- %s seconds ---" % (time.time() - start_time))
    print('- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ')

 

 

 

5. 실행 결과

 

일단은 단순히 출력하는 것으로 코딩했습니다만, 

txt 파일로 저장할 수도 있고, 

엑셀 파일로 저장할 수도 있으며,

아직 해보지는 않았지만, 구글 스프레드시트에 저장시킬 수도 있습니다. 

 

뿐만 아니라, 동적 페이지도 크롤링 가능합니다.

사실 이 부분 때문에 파이썬에 입문하게 되었지요.

 

파이썬, 정말 대단해요..

 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
[2022-05-29 18:29:04]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[1] [OCI] / 40,237(백만원) / 336(천주) / +3.24%
[2] [KODEX 200] / 23,588(백만원) / 685(천주) / +1.06%
[3] [POSCO홀딩스] / 20,538(백만원) / 70(천주) / 0.00%
[4] [한화솔루션] / 19,484(백만원) / 563(천주) / +1.13%
[5] [HMM] / 19,388(백만원) / 595(천주) / +3.53%
[6] [삼성바이오로직스] / 17,548(백만원) / 21(천주) / -0.71%
[7] [LG에너지솔루션] / 17,432(백만원) / 40(천주) / 0.00%
[8] [NAVER] / 14,157(백만원) / 52(천주) / +1.50%
[9] [하나금융지주] / 11,923(백만원) / 248(천주) / +1.76%
[10] [SK] / 10,885(백만원) / 46(천주) / +0.85%
[11] [현대미포조선] / 9,009(백만원) / 110(천주) / +0.48%
[12] [삼성전자우] / 8,979(백만원) / 150(천주) / +0.50%
[13] [팬오션] / 8,883(백만원) / 1,108(천주) / +1.00%
[14] [KT&G] / 7,770(백만원) / 92(천주) / +0.12%
[15] [현대차] / 7,746(백만원) / 42(천주) / +0.82%
[16] [우리금융지주] / 7,089(백만원) / 478(천주) / +0.34%
[17] [TIGER 200] / 7,049(백만원) / 204(천주) / +1.04%
[18] [엔씨소프트] / 6,636(백만원) / 14(천주) / -0.77%
[19] [LG생활건강] / 5,855(백만원) / 8(천주) / +1.28%
[20] [TIGER 차이나전기차SOLACTIVE] / 5,585(백만원) / 429(천주) / -0.65%
[21] [KT] / 5,494(백만원) / 149(천주) / +2.42%
[22] [기아] / 5,450(백만원) / 66(천주) / +0.61%
[23] [KODEX 레버리지] / 5,285(백만원) / 297(천주) / +2.20%
[24] [후성] / 4,996(백만원) / 195(천주) / -9.38%
[25] [SK이노베이션] / 4,761(백만원) / 23(천주) / +1.93%
[26] [백광산업] / 4,587(백만원) / 801(천주) / -0.35%
[27] [한국전력] / 4,549(백만원) / 191(천주) / 0.00%
[28] [롯데케미칼] / 4,488(백만원) / 23(천주) / +1.53%
[29] [SK텔레콤] / 4,321(백만원) / 76(천주) / +0.35%
[30] [PI첨단소재] / 4,231(백만원) / 88(천주) / +0.21%
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
[Total] --- 19.224879503250122 seconds ---
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

 

 

 

6. 마치며..

 

실제로 크롤링을 위해 코드를 작성하고 실행을 시키다보면 여러가지 경우의 난관에 이르는 경우가 많습니다. 

 

예를 들자면.. 저는 아래 3가지를 주로 사용하는데요,

 

driver.find_element_by_xpath()
soup.select()
soup.select_one()

 

처음부터 이것 저것 다 써본 것은 아니고요. 

처음 배운 한 가지만 썼었는데, 가끔 잘 안될 때가 있더라고요. 

그래서 구글링했습니다. 헛헛..

아무튼 구글링을 열심히 하셔서, 이것 저것 다 사용하다 보면 본인에게 편한 게 있을 겁니다. 

 

다음부터는 이런 경험들을 하나 둘 정리해보도록 하겠습니다. 

 

 

728x90
반응형
Comments