我正在尝试获取html页面的正文内容。

假设此html文件:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <link href="../Styles/style.css" rel="STYLESHEET" type="text/css" />

  <title></title>
</head>

<body>
<p> text 1 </p>
<p> text 2 </p>
</body>
</html>


我想要的是:

<p> text 1 </p>
<p> text 2 </p>


因此,我认为使用SAXParser可以做到这一点(如果您知道更简单的方法,请告诉我)

这是我的代码,但我总是将null作为正文内容:

private final String HTML_NAME_SPACE = "http://www.w3.org/1999/xhtml";
private final String HTML_TAG = "html";
private final String BODY_TAG = "body";
public static void parseHTML(InputStream in, ContentHandler handler) throws IOException, SAXException, ParserConfigurationException
{
    if(in != null)
    {
        try
        {
            SAXParserFactory parseFactory = SAXParserFactory.newInstance();
            XMLReader reader = parseFactory.newSAXParser().getXMLReader();
            reader.setContentHandler(handler);
            InputSource source = new InputSource(in);
            source.setEncoding("UTF-8");
            reader.parse(source);
        }
        finally
        {
            in.close();
        }
    }
}

public ContentHandler constrauctHTMLContentHandler()
{
    RootElement root = new RootElement(HTML_NAME_SPACE, HTML_TAG);
    root.setStartElementListener(new StartElementListener()
        {
        @Override
        public void start(Attributes attributes)
        {
            String body = attributes.getValue(BODY_TAG);
            Log.d("html parser", "body: " + body);
        }
    });
return root.getContentHandler();
}


然后

parseHTML(inputStream, constrauctHTMLContentHandler()); // inputStream is html file as stream


此代码有什么问题?

最佳答案

如何使用Jsoup?您的代码看起来像

Document doc = Jsoup.parse(html);
Elements elements = doc.select("body").first().children();
//Elements elements = doc.select("p");//or only `<p>` elements
for (Element el : elements)
    System.out.println("element: "+el);

关于java - 在Java中获取HTML文件的正文内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22045126/

10-08 23:46