使用TagSoup将HTML页面转换为XHTML

4
抱歉如果这个问题太简单了,但我找不到Java版本TagSoup的教程或文档。基本上,我想从互联网下载一个HTML网页并将其转换为包含在字符串中的XHTML。如何使用TagSoup实现此功能?
谢谢!
2个回答

9
像这样的东西:
wget -O - example.com/bad.html | java -jar tagsoup.jar

或者,从Java开始:

解析HTML:

  • 创建一个 org.ccil.cowan.tagsoup.Parser 的实例
  • 提供自己的 SAX2 ContentHandler
  • 提供引用HTML的 InputSource
  • 然后调用 parse()

准确无误!我想在Java中将这个值转换为字符串。 - konr
@konr,如果这个答案正是你想要的,请考虑接受/点赞它 =) - David Thomas

0

以下是代码,它应该为您提供一种方法来拉取一个网页并使用TagSoup进行解析...

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://streak.espn.go.com/en/?date=20120824");
        HttpResponse response = client.execute(request);

        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            throw new IOException("Invalid response from server: " + status.toString());
        }

        // Pull content stream from response
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        try
        {
            XMLReader parser = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser");

            // Use the TagSoup parser to build an XOM document from HTML
            Document doc = new Builder(parser).build(builder.toString());

            // Push your data to string or XML
            doc.toString();
            doc.toXML();
        }
        catch(IOException e)
        { ... }

3
下次请包含“import”语句。 - SeriousLee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接