5KY's Life

Python파이썬 - investing.com의 챠트 이미지로 저장하기 본문

Python파이썬

Python파이썬 - investing.com의 챠트 이미지로 저장하기

오키 5KY 2021. 9. 25. 17:49
728x90
반응형

매일 주식일기 포스팅을 하고있습니다. 주식일기 포스팅을 위해 investing.com에 들어가 각종 지표를 확인하고 챠트를 캡쳐해서 사용하고있습니다. 매번 반복적인 작업을 하려니 귀찮더군요. 그래서 파이썬으로 investing.com의 챠트를 이미지로 저장해주는 프로그램을 만들어 봤습니다. 포스팅 시간이 많이 단축될 것 같아요^^

 

Python으로 investing.com의 kospi 챠트를 이미지로 저장하는 코드입니다.

 

from selenium import webdriver
import time
from datetime import datetime

def kospi():

    # 오늘 날짜 가져오기
    today = datetime.today().strftime("%Y%m%d")

    # python파일과 동일한 폴더에 chromedriver.exe파일이 있어야 함.
    # python파일과 다른 폴더에 있으면 webdriver.Chrome()의 괄호 안에 chromedriver.exe 파일이 있는 경로를 입력해줘야 한다.
    driver = webdriver.Chrome()
    # driver = webdriver.Chrome('./chromedriver')   # Linux는 이 코드로 사용.

    # investing.com의 kospi로 이동
    driver.get('https://kr.investing.com/indices/kospi')
    time.sleep(1)

    # 웹화면 원화는 대로 맞추기
    driver.set_window_size(1920, 1080) #웹 화면 크기 조절
    driver.execute_script("window.scrollTo(0, 650)") # 웹 화면이 원화는 위치로 이동하도록 scroll down
    time.sleep(1)

    # 챠트를 봉차트, 일봉, 6개월로 설정하기 위한 클릭
    chart_type_button_path = '//*[@id="__next"]/div/div/div[3]/main/div/div[5]/div/div[1]/div/div[2]/div/cq-context/div[1]/div[1]/button[1]/img'
    driver.find_element_by_xpath(chart_type_button_path).click()
    time.sleep(2)
    chart_1day_button_path = '//*[@id="__next"]/div/div/div[3]/main/div/div[5]/div/div[1]/div/div[2]/div/cq-context/div[1]/div[2]/button[7]/span'
    driver.find_element_by_xpath(chart_1day_button_path).click()
    time.sleep(2)
    chart_6month_button_path = '//*[@id="__next"]/div/div/div[3]/main/div/div[5]/div/div[1]/div/div[2]/div/cq-context/div[2]/div[4]/ul/li[5]/button'
    driver.find_element_by_xpath(chart_6month_button_path).click()
    time.sleep(2)

    # 챠트 부분 이미지 데이터로 가져오기
    element = driver.find_element_by_class_name("overview-chart-context ")
    element_png = element.screenshot_as_png

    # image byte를 file open을 이용하여 png 파일로 저장.
    with open('./captures/'+today+'/kospi.png', 'wb') as file:
        file.write(element_png)

    driver.quit()



if __name__ == '__main__':
    kospi()

 

 

※ 실행환경1

Python 3.9.1

Windows 10

Pycharm 2021.2.2(Community Edition)

 

※ 실행환경2

Python 2.7.18

Ubuntu 20.04.2 LTS

Pycharm 2021.1.3(Community Edition)

 

728x90
반응형