【问题标题】:Fatal Error while parsing web page with javax.xml.parsers.DocumentBuilder使用 javax.xml.parsers.DocumentBuilder 解析网页时出现致命错误
【发布时间】:2012-08-08 00:26:45
【问题描述】:

我正在编写一个解析网页的程序(我无权访问,因此无法修改它)。

首先我连接并使用 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>

我怎样才能克服这个异常?

【问题讨论】:

标签: java html html-parsing sax saxparser


【解决方案1】:

Html 不是有效的 xml。使用 xml 解析器来解析 html 可能会导致很多错误(正如您已经发现的那样)。

您的 html 失败的原因是您的 Doctype 声明:

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

xml 解析器期望“PUBLIC”文档类型声明如下所示:

<!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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    相关资源
    最近更新 更多