Jsoup을 이용해서 네이버 스포츠 크롤링(https://sports.news.naver.com/wfootball/index)
public class Project02_A {
public static void main(String[] args) {
// Jsoup API
String url="https://sports.news.naver.com/wfootball/index";
Document doc=null;
try {
doc=Jsoup.connect(url).get();
}catch(Exception e) {
e.printStackTrace();
}
Elements element=doc.select("div.home_news");
String title=element.select("h2").text().substring(0, 4);
System.out.println("===========================");
System.out.println(title);
System.out.println("===========================");
for(Element el:element.select("li")) {
System.out.println(el.text());
}
System.out.println("===========================");
}
}
크롤링 할 URL(준비)
Document 객체 생성
doc=Jsoup.connect(url).get();
get방식으로 요청
doc에 html 요소들이 들어 있음.
개발자 도구로
파악
css로 즉 class 이름으로 접근 할 수 있음.
div에 home_news라는 클래스를 찾아가라.
혹시라도, home_news가 여기만 있는게 아니라 다른 데도 여러 개 있기 때문에 Elements 배열로 받아야 한다.
헤더 부분의 제목을 가져온다.
String title=element.select("h2").text().substring(0,4);
추천뉴스
하위 뉴스 기사들을 for문을 돌면서 출력
element.select("li") 여러개가 리턴 Element 타입으로
텍스트 값 출력
System.out.println(el.text());
'자바TPC 프로젝트' 카테고리의 다른 글
P3 Excel에 이미지 저장하기(2) (0) | 2022.02.06 |
---|---|
P3 Excel파일 Reading하기 (1) ClassNotFoundException: org.apache.xmlbeans.XmlObject 에러해결 (0) | 2022.02.06 |
P2 Jsoup API를 이용하여 웹 페이지 Crawling 하기(1) (0) | 2022.02.04 |
P1. 주소를 입력하면 위도와 경도를 추출하는 프로그래밍(3) (0) | 2022.02.04 |
P1. 주소를 입력하면 위도와 경도를 추출하는 프로그래밍(2) (0) | 2022.02.04 |