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>
내가 원하는 것은 :
이 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
이 코드에 문제가 있나요?
쉬운 방법 - html 구문 분석을 위해 [jsoup] (http://jsoup.org/)를 고려하십시오. [here] (http://stackoverflow.com/questions/22043592/trying-to-extract-content-from-url)를 참조하십시오. -in-java/22043838 # 22043838) – PopoFibo
'start' 메소드에서 어떤'attributes'를 얻었는지 확인 했습니까? 올바르게 기억한다면 콜백은 모든 시작 요소에 대해 호출됩니다. – Smutje
@PopoFibo : 나는 jsoup에 익숙하지 않기 때문에 내가 사용하지 않는 한 그것을 사용하지 않는 편이 좋다. – mehdok