2014-02-26 7 views
1

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 

이 코드에 문제가 있나요?

+1

쉬운 방법 - html 구문 분석을 위해 [jsoup] (http://jsoup.org/)를 고려하십시오. [here] (http://stackoverflow.com/questions/22043592/trying-to-extract-content-from-url)를 참조하십시오. -in-java/22043838 # 22043838) – PopoFibo

+0

'start' 메소드에서 어떤'attributes'를 얻었는지 확인 했습니까? 올바르게 기억한다면 콜백은 모든 시작 요소에 대해 호출됩니다. – Smutje

+0

@PopoFibo : 나는 jsoup에 익숙하지 않기 때문에 내가 사용하지 않는 한 그것을 사용하지 않는 편이 좋다. – mehdok

답변

2

사용 방법은 Jsoup일까요? 당신이 HTML을 잡는 방법 코드는

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); 
+0

감사합니다. 나는 이것을 시도 할 것입니다. – mehdok

1

확실하지처럼 보일 수 있습니다. 로컬 파일이면 Jsoup에 직접로드 할 수 있습니다. 일부 URL에서 가져와야하는 경우 일반적으로 Apache의 HttpClient를 사용합니다. 빠른 시작 가이드는 여기에 있습니다 : HttpClient 그리고 시작하기에 좋은 직장입니다. 이 데이터는 다시이 같은 일을 얻을 수

: 다음

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost(URL); 
// 
// here you can do things like add parameters used when connecting to the remote site  
// 
HttpResponse response = client.execute(post); 
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

(Pshemo에 의해 제안 된 바와 같이) 나는 Jsoup 데이터를 분석하고 추출하기 위해 사용을 Jsoup

Document document = Jsoup.parse(HTML); 
// OR 
Document doc = Jsoup.parseBodyFragment(HTML); 
Elements elements = doc.select("p"); // p for <p>text</p> 
+0

감사합니다, 내 HTML 로컬 파일, 그래서 만약 내 방식으로 작동하지 않았다면 jsoup 함께 갈 것입니다 – mehdok