2012-08-10 39 views
3

我正在编写解析网页的程序(其中一个我无法访问,所以无法修改)。使用javax.xml.parsers.DocumentBuilder解析网页时发生致命错误

首先我连接并使用getContent()获取页面的InputStream。那里没有问题。

但随后在解析时:

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抛出:

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> 

我该如何克服这个异常?

+1

我不认为这是一个好主意,使用XML解析器来解析HTML。 – Alex 2012-08-10 17:01:47

+0

那我该用什么? – dspyz 2012-08-10 17:04:42

+0

http://stackoverflow.com/questions/9071568/parse-web-site-html-with-java – Alex 2012-08-10 17:07:02

回答

2

Html无效xml。使用xml解析器解析html可能会导致很多错误(如您已经发现的)。

你的HTML失败的原因是因为你的DOCTYPE声明:

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

XML解析器想到 '公' DOCTYPE声明如下所示:

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

如果你可以” t改变html页面,我不确定你可以做些什么。也许你可以修改/包装你的输入流来添加一些虚拟数据,使其符合预期的要求,或删除文档类型声明。

您应该改用HTML解析库。我不知道我的头顶上有什么,但是这个(旧的)帖子似乎列出了一对。 http://www.benmccann.com/blog/java-html-parsing-library-comparison/。搜索谷歌也回来了http://jsoup.org/

相关问题