Created
September 24, 2020 06:55
-
-
Save youngjinmo/5ed65f5fcc9d419a4228677c9f2449d5 to your computer and use it in GitHub Desktop.
네이버 증권에서 코스피 인덱스 크롤링하기, 스케줄러 이용하여 5초에 한 번 씩 자동 크롤링
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package parseJsoup; | |
import java.io.IOException; | |
import java.util.Timer; | |
import java.util.TimerTask; | |
import org.jsoup.Jsoup; | |
import org.jsoup.nodes.Document; | |
import org.jsoup.select.Elements; | |
public class extractKospi { | |
public static void main(String[] args) throws IOException { | |
String url = "https://finance.naver.com/"; | |
Document doc = Jsoup.connect(url).get(); | |
System.out.println(doc.title()); | |
taskScheduler(doc); | |
} | |
static String getIndex(Document doc) throws IOException { | |
String kospi_index_selector = ".kospi_area > div:nth-child(1) > a:nth-child(2) > span:nth-child(1) > span:nth-child(1)"; | |
// 네이버 증권에서 코스피 지수 크롤링 | |
Elements kospiIndex = doc.select(kospi_index_selector); | |
return kospiIndex.text(); | |
} | |
static String getPer(Document doc) throws IOException { | |
String kospi_per_selector = ".kospi_area > div:nth-child(1) > a:nth-child(2) > span:nth-child(1) > span:nth-child(3)"; | |
// 네이버 증권에서 코스피 변화율 크롤링 | |
Elements kospiPer = doc.select(kospi_per_selector); | |
return kospiPer.text(); | |
} | |
// scheduler 이용해서 5초에 한 번씩 함수 실행 | |
static void taskScheduler(Document doc) { | |
Timer autoExecution = new Timer(); | |
TimerTask timer = new TimerTask() { | |
@Override | |
public void run() { | |
try { | |
System.out.println(getIndex(doc)); | |
System.out.println(getPer(doc)); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
}; | |
autoExecution.schedule(timer, 1000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment