2012-08-10 4 views
3

웹 페이지를 구문 분석하는 프로그램을 작성하고 있습니다 (수정할 수 없도록 액세스 할 수없는 프로그램).javax.xml.parsers.DocumentBuilder를 사용하여 웹 페이지를 구문 분석하는 중 치명적인 오류가 발생했습니다.

먼저 getContent()를 연결하여 페이지의 InputStream을 가져옵니다. 거기에 문제가 없습니다.

그러나 구문 분석 :

org.xml.sax.SAXParseException; lineNumber: 3; columnNumber: 64; The system identifier must begin with either a single or double quote character. 
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:253) 
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:288) 
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121) 
    at cs.ualberta.lgadapter.LGAdapter.parseMoveGameList(LGAdapter.java:78) 
    ... 

내가 구문 분석하고 있습니다 (단, 변경할 수 없습니다) 페이지

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" > 









<html> 
<head> 
<META http-equiv="Expires" content="0" /> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
<!-- ... --> 
</head> 
<body> 
<!-- ... --> 
</body> 
</html> 
다음과 같습니다

public static int[] parseMoveGameList(InputStream is) throws ParserConfigurationException, IOException, SAXException { 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder = dbf.newDocumentBuilder(); 
     Document doc = builder.parse(is); 
     /*...*/ 
    } 

여기 builder.parse 발생

이 예외를 어떻게 피할 수 있습니까?

+1

XML 구문 분석기를 사용하여 HTML을 구문 분석하는 것은 좋지 않습니다. – Alex

+0

그 때 나는 무엇을 사용해야합니까? – dspyz

+0

http://stackoverflow.com/questions/9071568/parse-web-site-html-with-java – Alex

답변

2

HTML이 유효하지 않습니다. xml. xml 파서를 사용하여 html을 구문 분석하면 많은 오류가 발생할 수 있습니다 (이미 발견했듯이).

당신의 HTML이 실패 이유 때문에 당신의 DOCTYPE 선언이다 :

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" > 

XML 파서는 'PUBLIC'DOCTYPE 선언은 다음과 같이 예상 : 당신이 할 수있는 경우

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "FALLBACK PATH TO DTD" > 

' html 페이지를 변경하면, 이것에 대해 할 수있는 일이 많지 않은 것인지 확신 할 수 없습니다. 어쩌면 당신은 입력 스트림을 수정/감싸서 더미 ​​데이터를 추가하여 기대 한 것과 일치하도록 만들거나 doctype 선언을 제거 할 수 있습니다.

대신 HTML 구문 분석 라이브러리를 사용해야합니다. 나는 내 머리 꼭대기에서 어떤 것이 있는지 모르지만,이 (오래된) 게시물에는 부부 목록이있는 것 같다. http://www.benmccann.com/blog/java-html-parsing-library-comparison/. Google을 검색 할 때도 마찬가지입니다. http://jsoup.org/

관련 문제