본문 바로가기
programming/python-sample

python3 - Crawler (Investing.com 원자재 데이터 읽기)

by sniffer-k 2023. 6. 3.

"Investing.com " 웹사이트에서는 전세계 다양한 주식/선물/ETF등등 정보를 무료로 공개한더

 

본 문서에서는 Investing.com 사이트에서 "천연가스 선물" 데이터의 과거 데이터를 읽는 크롤링 코드에 대해 설명한다

 

크롤링을 수행하기 위해서는 대상 페이지의 기본적인 구조를 알아야한다. "천연가스 선물 " 페이지의 과거데이터 부분 페이지 구조는 다음과 같다.

 

Investing.com -> 천연가스 항목 / 구조

 

해당 페이지에서 천연가스 데이터를 크롤링하기 위해 분석한결과, 분석 대상 페이지에서는 "<table , class : "datatable_table__D_jso datatable_table--border__B_zW0 datatable_table--mobile-basic__W2ilt datatable_table--freeze-column__7YoIE"  ~ >" 을 먼저 찾아야한다. 

위 그림과 같이 테이블 정보를 먼저 찾고 그 하위에 tbody (과거 데이터 테이블 몸체) 그리고 각 일자별 데이터 정보는 tr, "datatable_row_qHMpQ" 클래스로 구성되어있다.

표 테이블의 각각의 행은 <td class= ""  ~ > 가 배열로 들어있다. (각 행별 td class 이름은 랜덤이다 )

 

구조 분석만 되면 크롤링은 매우 쉽다.

 

단 페이지를 읽어오는 메인 함수만 바꿔야한다 (Investing.com 사이트는 안티 크롤러 서비스가 있음 ,"cloudflare" ) 

 

cloudflare에 대한 파이썬 모듈 기본 사용법은 이전에 메모하였으니... 크롤링 샘플 코드는 다음과 같다

 

import cloudscraper
from bs4 import BeautifulSoup

scraper = cloudscraper.create_scraper(disableCloudflareV1=True)

html = scraper.get("https://kr.investing.com/commodities/natural-gas-historical-data").content

soup = BeautifulSoup(html,'html.parser')

dage_index = 0

sub_root = soup.find('table',class_='datatable_table__D_jso datatable_table--border__B_zW0 datatable_table--mobile-basic__W2ilt datatable_table--freeze-column__7YoIE')

for sub_body in sub_root.find('tbody',class_='datatable_body__cs8vJ').find_all('tr'):


	print(f'--------------------------')
	
	day_info = ""
	close_value = ""
	open_value  = ""
	high_value  = ""
	low_value   = ""
	volume_value = ""

	#for table_row in sub_body.find_all('td'):
	table_row = sub_body.find_all('td')

	day_info 	= table_row[0].get_text()	
	close_value = table_row[1].get_text()
	open_value  = table_row[2].get_text()
	high_value  = table_row[3].get_text()
	low_value   = table_row[4].get_text()	
	volume_value = table_row[5].get_text()

	print(f'{dage_index} {day_info} : {close_value} | {open_value} | {high_value} | {low_value} | {volume_value}')

	dage_index = dage_index + 1

	print(f'--------------------------')

print(f'all job done ')

 

수행결과는 다음과 같다

 

크롤링 결과 비교

 

크롤링이 잘되는것을 알수있다 .. 물론 과거 데이터를 계속 읽기 위해서는 다음페이지의 데이터를 추가적으로 요청하는 코드가 있어야된다.  

샘플코드는 여기까지 ...

728x90