본문 바로가기

Python/crawling

[Python] selenium을 활용하여 해외 증시 정보 크롤링하기

selenium을 활용해 간단하게 네이버 금융 페이지에서 해외증시 정보를 가져와보았다.

(https://github.com/aruymeek/python_Selenium/tree/master/chrometest)

 

1. selenium 설치

selenium 모듈을 import 하기에 앞서 설치를 먼저 해준다.

!pip install selenium

설치하면 selenium이 정상적으로 import 되는 것을 확인할 수 있다.

from selenium import webdriver

 

2. 클래스 생성하기

이번에도 class를 하나 만들어서 정보를 간편하게 다룰 수 있게 해주었다.

class StockModel:

    def __init__(self, _nat, _idx, _now, _diff, _pct):
        self.nation = _nat
        self.index = _idx
        self.now = _now
        self.diff = _diff
        self.percent = _pct

    def SaveFormat(self):
        line = '{0};{1};{2};{3};{4}'.format(self.nation, self.index, self.now, self.diff, self.percent)

        return line

    def ReadFormat(self):
        if self.percent < 0:
            line = '[{0}] {1} | 현재가: {2} (전일대비 ▼{3}) | 등락률: {4}%'.format(self.nation, self.index, self.now, self.diff, self.percent)
        else:
            line = '[{0}] {1} | 현재가: {2} (전일대비 ▲{3}) | 등락률: {4}%'.format(self.nation, self.index, self.now, self.diff, self.percent)

        return line

StockModel 클래스로 만든 객체들은 nation(국가), index(지수), now(현재가), diff(전일대비) percent(등락률) 등의 속성을 가지고 있다. 

 

SaveFormat 메서드는 가져온 정보들을 txt 파일로 저장할 형식으로 변환해주는 역할을 한다. ReadFormat는 반대로 txt 파일에서 정보를 읽어올 때의 형식으로 변환하여 출력해주는 메서드이다.

 

3. chormedriver 사용하기

driver = webdriver.Chrome()
url = 'https://finance.naver.com/world'
driver.get(url)

chrome을 열어 지정한 url로 이동한다.

 

위는 네이버 금융 페이지의 소스 코드를 확인한 부분이다. id가 'americaIndex'인 <table> 태그를 찾으면 그 안에 <tr> 태그들이 여러개 존재하는 것을 확인할 수 있다.

 

.find_element_by_xpath() 혹은 .find_elements_by_xpath()를 이용하여 xpath를 통해 원하는 부분의 web element를 가져올 수 있다.

table = driver.find_element_by_xpath('//*[@id="americaIndex"]')
trs = table.find_elements_by_xpath('.//tr')

두번째 줄에서 xpath 앞에 '.'이 붙은 이유는, table의 하위 소스 코드에서 <tr> 태그가 들어간 부분을 찾아낼 수 있도록 하기 위함이다.

 

<tr> 태그 하위 소스 코드들을 잘 살펴보면, <th> 태그들로 이루어져있는 것과 <td> 태그들로 이루어져있는 것이 있다. <th> 태그는 해당 표의 열 머리글 부분을 나타내므로 <td> 태그를 찾아야 원하는 정보를 추출할 수 있다.

 

stockList = []

for tr in trs:
    tds = tr.find_elements_by_xpath('.//td')

    if len(tds) == 0:
        continue
        
    else:
        nation = tds[0].text
        index = tds[1].text
        now = float(tds[2].text.replace(',', ''))
        diff = float(tds[3].text.replace(',', ''))
        percent = float(tds[4].text.replace('%', ''))

        stock = StockModel(nation, index, now, diff, percent)
        stockList.append(stock)

<tr> 안에 <td> 태그의 갯수가 0개이면 패스하고, nation(국가), index(지수), now(현재가), diff(전일대비) percent(등락률) 등의 정보를 추출한다. 그리고 StockModel 클래스로 stock이라는 인스턴스를 만들고 stockList에 하나씩 추가한다.

 

4. txt 파일 저장/읽기

stockList에 담긴 정보를 SaveFormat 메서드를 활용해 한 줄씩 txt 파일에 저장한다.

f = open(r'C:\Users\Desktop\stock.txt', 'w', encoding="utf-8")

for stock in stockList:
    line = stock.SaveFormat()

    f.write(line)
    f.write('\n')

f. close()

 

저장된 stock.txt 파일을 읽어 온 후 다시 StockModel 클래스를 이용해 stock 객체를 만들어 준다.

f = open(r'C:\Users\Desktop\stock.txt', 'r', encoding="utf-8")

lines = f.readlines()
stock_list = []

for line in lines:
    items = line.split(';')

    nation = items[0].strip()
    index = items[1].strip()
    now = format(float(items[2].strip()), ',')
    diff = float(items[3].strip())
    percent = float(items[4].strip())

    stock = StockModel(nation, index, now, diff, percent)
    stock_list.append(stock)

 

ReadFormat 메서드를 활용해서 위에서 지정해둔 형식에 맞춰 출력해볼 수 있다.

for s in stock_list:
    data = s.ReadFormat()
    print(data)