Java는 Jsoup을 통해 HTML 파일을 구문 분석합니다.

1. Jsoup 소개

Jsoup은 URL 주소와 HTML 텍스트 콘텐츠를 직접 구문 분석 할 수있는 Java HTML 파서입니다. 이는 jQuery와 유사한 DOM, CSS 및 운영 방법을 통해 데이터를 검색하고 조작 할 수있는 매우 노동 절약적인 API를 제공합니다.

둘째, Jsoup의 주요 기능

1. URL, 파일 또는 문자열에서 HTML 구문 분석

2. DOM 또는 CSS 선택기를 사용하여 데이터를 찾고 검색합니다.

3. 작동 가능한 HTML 요소, 속성 및 텍스트

참고 : jsoup은 MIT 프로토콜을 기반으로 출시되었으며 상업용 프로젝트에서 안심하고 사용할 수 있습니다.

셋, Jsoup 사용법 소개

1. Document 개체 얻기

Document document = Jsoup.parse(new File("D:\\information\\test.html"), "utf-8");

2. DOM을 사용하여

Document 객체를 얻은 후 다음 단계는 Document 객체를 구문 분석하고 여기에서 원하는 요소를 가져 오는 것입니다.

문서는 지정된 요소를 얻기위한 다양한 방법을 제공합니다.

  1. getElementById (String id) : ID로 가져 오기
  2. getElementsByTag (String tagName) : 태그 이름으로 가져 오기
  3. getElementsByClass (String className) : 클래스 이름으로 가져 오기
  4. getElementsByAttribute (String key) : 속성 이름으로 가져 오기
  5. getElementsByAttributeValue (String key, String value) : 속성 이름 및 속성 값을 지정하여 가져옵니다.
  6. getAllElements () : 모든 요소 가져 오기

3. 선택기를 통해 요소 찾기

css 또는 jQuery와 유사한 선택기를 통해 요소 찾기

Element 클래스의 다음 메서드가 사용됩니다.

public Elements select(String cssQuery)

CSS 또는 jQuery와 유사한 선택기 문자열을 전달하여 지정된 요소를 찾습니다.

네, Jsoup 코드 예제

블로그의 원래 의도는 HTML에서 테이블을 구문 분석하고이를 Bean으로 변환하는 것입니다.

1. 의존성 소개

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.12.1</version>
</dependency>

2. 코드 예

//通过Jsoup获取table中对应标签的信息
private static void HTMLParserMapInit() throws IOException {
		Document document = Jsoup.parse(new File("D:\\information\\test.html"), "utf-8");
        Elements table_title = document.select(".title");
        Elements tables = document.select(".left");
        for(int i=0;i<table_title.size();i++) {
        	String title = table_title.get(i).text();
            String keyLevel1 = "";
		    String keyLevel2 = "";
		    String value = "";
		    String tag_rowspan = "";
		    String tag_colspan = "";
		    String tag_class = "";
		    String tag_text = "";
		    String title = "";
            String table = tables.get(i);
		    Elements tr =  table.select("tr");
		    for(Element eTr : tr){
			    Elements td = eTr.select("td");
			    for(Element eTd : td){
				    tag_rowspan = eTd.attr("rowspan");
				    tag_colspan = eTd.attr("colspan");
				    tag_class = eTd.attr("class");
				    tag_text = eTd.text();
				    if(!tag_colspan.equals("")) {
					    title += tag_text + ",";
				    }
				    if((tag_class.equals("class2"))) {
					    keyLevel1 = tag_text;
				    }else if((tag_class.equals("class1"))) {
					    keyLevel2 = tag_text;
				    }else if(tag_class.equals("")){
					    value += tag_text+",";
				    }
			        }
			    if(!(keyLevel1.equals("")&&keyLevel1.equals(""))) {
				    if(!value.equals("")) {
					    value = value.substring(0,value.length() - 1);
					    shiftInformationHashMap.put(keyLevel1 + "," + keyLevel2, value);
				    }
				        value = "";                                                                                                                                             
                }
		    }
		    title = title.toString().substring(0,title.length() - 1);
		    System.out.println("title,"+title);
		    System.out.println("hashMap,"+shiftInformationHashMap.toString());
				
		}
	}

HTML의 데이터를 해시 맵으로 구문 분석하면 모든 것이 한 눈에 명확 해집니다.

다섯, 콩에 매핑

public static <T, V> T map2Bean(Map<String,V> map,Class<T> clz) throws Exception{
	T obj = clz.newInstance();
	Field field = null;
	for(String key : map.keySet()) {
		field = obj.getClass().getDeclaredField(key);
		field.setAccessible(true);
		field.set(obj, map.get(key));
	}
	return obj;
}

여섯, CSV 파일 구문 분석

1. CSV 파일

2. 빈 클래스

@Data
public class ScoreBean {
	private Object id;
	private Object score;
}

 3. CSV 파일 읽는 방법

​public static List<HashMap<String, Object>> readCSVToList(String filePath) throws Exception {
	List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
	BufferedReader reader = null;
	try {
		reader = new BufferedReader(new FileReader(filePath));
        String[] headtilte = reader.readLine().split(",");
        String line = null;
        while ((line = reader.readLine()) != null) {
        	HashMap<String, Object> hashMap = new HashMap<String, Object>();
            String[] itemArray = line.split(",");
            for (int i = 0; i < itemArray.length; i++) {
            	hashMap.put(headtilte[i], itemArray[i]);
            }
            list.add(hashMap);
        }
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (null != reader) {
			reader.close();
		}
	}
	return list;
}

4. 테스트 

public static void main(String[] args) throws Exception {
	String path = "D:\\scoreInfo.csv";
	    List<HashMap<String, Object>> list = readCSVToList(path);
	    for(HashMap hashMap:list) {
	        BeanUtil.HashMapToBeanUtil(hashMap,ScoreBean.class);
	    }
}

5. 콘솔 출력

 

과거의 하이라이트 :

Java 지식 시스템 요약 (2021 버전)

자바 멀티 스레딩에 대한 기본 지식 요약 (절대 클래식)

매우 상세한 springBoot 연구 노트

일반적인 데이터 구조 및 알고리즘 요약

자바 디자인 패턴 : 23 개의 디자인 패턴에 대한 포괄적 인 분석 (매우 상세)

Java 인터뷰 질문 요약 (답변 포함)

추천

출처blog.csdn.net/guorui_java/article/details/114714216