1. 서문
최근에 직장에서 문제가 발생했습니다. 백엔드에는 시간이 지정된 작업이 있습니다. 법정 휴일, 주말 휴가, 직장 등을 판단하려면 Java를 사용해야합니다. 실제로, 국가의 휴일은 매년 다를 수 있고 인공적으로 설정되기 때문에 논리만으로는 중국의 법정 공휴일을 판단하는 것은 기본적으로 불가능합니다.
따라서 다른 수단에만 의존 할 수 있으며, 생각할 수있는 더 신뢰할 수있는 수단은 다음과 같습니다.
1. 네트워크 인터페이스 : 일부 데이터 서비스 제공 업체는 요금 또는 횟수의 한계 등을 제공합니다. 효과는 이상적이지 않으며 제어 가능성이 좋지 않습니다. 나는 그것을 시도한 적이 없다.
https://www.juhe.cn/docs/api/id/177/aid/601
또는
http://apistore.baidu.com/apiworks/servicedetail/1116.html
2. 온라인으로 웹 페이지 정보를 분석하고 휴일 상황을 얻으십시오. 구문 분석 웹 페이지에 크게 의존하므로 웹 사이트를 선택할 때는 웹 사이트를 선택할 때 약간 더 신뢰할 수있는 웹 사이트를 찾아야합니다.
3. 법정 공휴일에 대한 국가 규정에 따르면 고객이 문제를 두려워하지 않으면 매년 시스템에 들어갑니다. 여전히 비교적 신뢰할 수 있습니다.
이 데모는 구현할 두 번째 데모를 선택합니다.
2. htmlunit을 사용하여 온라인으로 웹 페이지 정보를 분석하여 휴가 상황을 얻습니다.
처음에는 JSOUP을 사용하여 웹 페이지를 구문 분석했지만 그 효과는 이상적이지 않았습니다. 웹 페이지가 동적으로 생성되면 JSOUP에 다양한 문제가 발생하여 htmlunit로 변경했습니다. 일반적으로 Htmlunit은 여전히 매우 강력하고 브라우저의 작동을 시뮬레이션 할 수 있으며 Java 브라우저의 오픈 소스 구현으로 알려져 있습니다.
먼저 공식 웹 사이트로 이동하여 관련 JAR 패키지를 다운로드하고 관련 문서를 읽으십시오.
http://htmlunit.sourceforge.net/
여기서 분석중인 웹 페이지는 360 만 개의 영구 달력입니다.
http://hao.360.cn/rili/
캘린더 인터페이스는 다음과 같습니다.
구문 분석 된 HTML 형식은 다음과 같습니다.
구현 단계 :
1. 페이지를로드하십시오.
2. 페이지가로드 될 때까지 기다리기 위해 루프 (JavaScript를 사용하여 생성 된 일부 동적 페이지가있을 수 있음);
3. 웹 페이지 형식에 따라 HTML 컨텐츠를 파르시하고 주요 정보를 추출하여 캡슐화 된 객체에 저장합니다.
메모:
1. 어려움은 휴가를 가야하는지 여부와 휴가 유형을 결정하는 데 있습니다. 원본 페이지는 매일 휴가 유형을 나타내지 않기 때문에 여기서 논리를 직접 구현해야합니다. 자세한 내용은 코드를 참조하십시오.
2. 정적 최신 VocationName 변수의 이유는 다음 상황을 방지하기 때문에 (이 상황의 확률은 매우 낮습니다.
코드 구현 :
중국 날짜 클래스 정의 :
package com.pichen.tools.getDate; import java.util.date; public class chinadate {/*** gregorian time*/private date solardate;/*** 음력 날*/개인 문자열 음력;/*** Gregorian Day*/private string*/private string isvacation =/*** if a a firally; "비 면화";/*** 클래스*/개인 부울 isworkflag = false; 개인 부울 asuathday = false; 개인 부울 issunday = 거짓;/*** @solardate*/public date getSolardate () {return solard; Solardate;}/*** @return The Lunar*/public String getLunar () {return Lunar;}/*** @Param Lunar 설정*/public void setlunar (String Lunar) {this.lunar = 음력; set*/public void setsolar (String Solar) {this.solar = solar;}/*** @isvacation*/public boolean isvacation () {return isvacation;}/*** @param isvacation set*/public void setvacation (boolean isvacation) {thistor revacation = isvacation; VacationName*/public string getVacationName () {return VacationName;}/*** @param 휴가 이름 설정*/public void setVacationName (String VacationName) {휴가지 = 휴가 이름;}/*** @return isworkflag*/public boolean isworkflag on}/** *** @*** @param isworkflag; set*/public void setworkflag (boolean isworkflag) {this.isworkflag = isworkflag;}/*** @issaturday*/public boolean isaturday () {return isaturday;}/*** @param issaturday theatatuatday*/public void set aturday (boolean isaturday) {this. issunday*/public boolean issunday () {return issunday;}/*** @param issunday issunday*/public void setsunday (boolean issunday) {this.issunday = issunday;}} 웹 페이지를 구문 분석하고 데모를 호출하고 이번 달의 세부 사항과 오늘의 세부 사항을 인쇄합니다.
package com.pichen.tools.getDate; import java.io.ioexception; import java.net.malformedurlexception; import java.text.dateformat; import java.text.parseexception; import java.text.simpledateformat; import java.util.arraylist; import java.date; com.gargoylesoftware.htmlunit.failinghttpstatuscodeexception; import com.gargoylesoftware.htmlunit.webclient; import com.gargoylesoftware.htmlunit.html.domnodelist; import com.gargoylesoftware.htmlunit.html.htmllement; com.gargoylesoftware.htmlunit.html.htmlpage; public class main {private static string thice vocationname = ""; public string getVocationName (domnodelist <htmlelement> htmlelements, 문자열 날짜) parseexception {string rst = ""; simpledateformat ( "yyyy/mm/dd"); date paramdate = dateformat.parse (date); if (new date (). gettime (). gettime (). gettime (). gettime (). gettime (). i ++) {htmlElement element = htmlelements.get (i); if (element.getAttribute ( "class"). indexof ( "휴가")! = -1) {boolean hitflag = false; string votename = ""; for (; i <htmlelements.size (); i ++); lidate = elementtmp.getAttribute ( "date"); list <htmlelement> lunar = elementtmp.getElementsByattribute ( "span", "class", "lunar"); String lanartext = lunar.get (0); if (lanartext.equals ( "new year 's Day") if (lanartext.equals ( "New Year 's Eve") || lanartext.equals ( "Spring Festival")) {VoationName = "Spring Festival";} else if (lanartext.equals ( "Qingming")) {VoationName = "Spring Festival"; if (lanartext.equals ( "Dragon Boat Festival")) {VoationName = "Dragon Boat Festival";} else if (lanartext.equals ( "Mid-Autumn Festival")) {VoationName = "Mid-Autumn Festival";} else if (lanartext.equals ( "National Day")) {voationname = ""voationname = "" day ";} if (lidate.equals (date)) {hitflag = true;} if (elementtmp.getAttribute ("class "). indexof ("휴가 ") == -1) {break;}} if (hitflag == true &&! voationname.equals (" ") {rst = voationname;}}}}}}}}}}}}}}}} 실패 (드물게), 최신 vocation nameif (rst.equals ( "")) {system.out.println ( "경고 : html 페이지에서 직업 이름을 얻지 못하는 실패"); // 최신 vocation namersst = main.latestvocationnamame; else {true)에서 판단 할 수 있습니다. main.latestvocationName = rst;} return rst;} public list <CHINADATE> getCurrentDateInfo () {WebClient WebClient = null; list <chinadate> datelist = null; try {new SimpledateFormat ( "yyyy/mm/dd"); new arraylist <); webClient (); htmlpage page = webclient.getPage ( "http://hao.360.cn/rili/"); // (int k = 0; k <60; k ++) {if (! page.getEtlement ( "m-dates"). 페이지가로드되기를 기다리고 있습니다 요소 : htmlElements) {chinadate chinadate = new chinadate (); list <htmlelement> lunar = element.getElementsByattribute ( "span", "class", "lunar"); list <htmlelement> solar = element.getElementsByAttribute ( "div", "class", "solar"); chinadate.setlunar (lunar.get (0) .astext ()); chinadate.setsolar (solar.get (0)); chinadate.setsolardate (dateformat.parse (element.getAttribute (getattribute) DATE "))); if (element.getAttribute ("class "). indexof ("휴가 ")! = -1) {chinadate.setVacation (true); chinadate.setVacationName (this.getVocationName (htmlElements, 요소 .getAttribute ( "date"));} if (element.getAttribute ( "class"). indexof ( "주말")! = -10 && element.getAttribute ( "class"). indexof ( "last") ==-1) {chinadate.setsaturday (true);} if (exement.getAttribute ( "class") 주말 ")! = -1) {chinadate.setsunday (true);} if (element.getAttribute ("class "). indexof ("work ")! = -1) {chinadate.setworkflag (true);} else if (chinadate.issaturday () == false && chinadate.issunday () == false && chinadate.isvacation (). ) {chinadate.setworkflag (true);} else {chinadate.setworkflag (false);} datelist.add (chinadate);}} catch (예외 e) {e.printstacktrace (); system.out.println ( "http://hao.360.cn/rili/ rilli/ rilli/ rilli/ rili/ rili/ rili/ rilli/ rilli/ rilli/ rilli/ rili/ rili/ rili/ rili/ rili/ rilli/ rilli/ rili/. 마지막으로 {webclient.close ();} return datelist;} public chinadate getTodayInfo () {list <chinadate> datelist = this.getCurrentDateInfo (); dateformat dateformat = new SimpledateFormat ( "yyyy/mm/dd"); datelist) {if (dateformat.format (date.getSolardate ()). equals (dateformat.format (new date ()) {return return new chinadate ();} public static void main (strings) throws failinghttpStatuscodeexception, mullformedUrlexcection, INOUXCEMPLEMENT, INUPTEDENCEMPENTion {INPRUCEXCEMPLEMATION | datelist = new main (). getCurrentDateInfo (); chinadate today = new main (). getTodayInfo (); dateFormat DateFormat = new SimpledateFormat ( "yyyy/mm/dd"); System.out.out.println ( "이달의 세부 사항 :"); datelist) {system.out.println (dateformat.format (date.getSolardate ()) + "" + date.getVacationName());}System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- today.getSolarDate());System.out.println("Lunar: "+오늘 .getLunar ()); System.out.println ("Gregorian Calendar : "+Today.getSolar ()); System.out.println ("holiday name : "+today.getVacationName ()); System.out.println ("토요일 : "+tod ay.issaturday ()); System.out.out.out.out.out.println ("is sunday : " "+adoday.issunday ()); System.out.println ("휴가 중 : "+오늘. isvacation ());"Is Working Day : "+Today.isworkflag ()); System.out.println ("+main.latestvocationName);}}}}}}}} 프로그램을 실행하면 결과가 정확합니다.