2013-10-24 77 views
1

我想爲給定的URL提取文章的文本。從URL中提取文章文本

你知道它是否存在某些庫或現有代碼能夠做到這一點?

下面是URL的一個例子:http://fr.news.yahoo.com/france-foot-pro-vote-gr%C3%A8ve-fin-novembre-contre-125358890.html

感謝

問候

+2

http://stackoverflow.com/questions/3036638/how-to-extract-web-page-textual-content-in-java –

+0

只是在閒暇時對某些人 - https://開頭github上。 com/milosmns/goose - Android的鵝提取文本和其他信息,請參閱dev頁面以獲取更多信息。 – milosmns

回答

1

您需要使用JTomatoSoup其用途是:

刮,並從一個URL,文件解析HTML ,或字符串
使用DOM遍歷或CSS選擇器查找並提取數據
操縱HTML元素,屬性,以及對安全白名單文本
乾淨的用戶提交的內容,以防止XSS攻擊
輸出整潔HTML

該網站也有一個簡單上手的例子,但在這裏是SSCCE從Mykong:

import java.io.IOException; 

import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.nodes.Element; 
import org.jsoup.select.Elements; 

public class HTMLParserExample1 { 

    public static void main(String[] args) { 

    Document doc; 
    try { 

     // need http protocol 
     doc = Jsoup.connect("http://google.com").get(); 

     // get page title 
     String title = doc.title(); 
     System.out.println("title : " + title); 

     // get all links 
     Elements links = doc.select("a[href]"); 
     for (Element link : links) { 

      // get the value from href attribute 
      System.out.println("\nlink : " + link.attr("href")); 
      System.out.println("text : " + link.text()); 

     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    } 

} 

網站:http://jsoup.org/

0

我特別喜歡使用Apache HTTPClient庫。您可以非常輕鬆地創建HTTP請求,並根據需要解析結果。這是一個非常簡單的例子,使用你的URL(但不解析)。

import java.io.IOException; 

import org.apache.http.HttpHost; 
import org.apache.http.HttpResponse; 
import org.apache.http.ParseException; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.conn.params.ConnRoutePNames; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 


public class Test { 

    public static void main(String[] args) throws ParseException, IOException {  
     DefaultHttpClient httpclient = new DefaultHttpClient();  

     HttpGet httpget = new HttpGet("http://fr.news.yahoo.com/france-foot-pro-vote-gr%C3%A8ve-fin-novembre-contre-125358890.html"); 
     HttpResponse response = httpclient.execute(httpget); 
     String responseText = EntityUtils.toString(response.getEntity()); 
     EntityUtils.consumeQuietly(response.getEntity()); 

     System.out.println(responseText); 
    } 

} 
+0

但'JSoup'更好。這是非常美味,有益健康,你知道嗎? :D –

+0

我通常將Apache用於JSON Web服務,因此在這種情況下它可能不是最簡單的。我想,我大多比較喜歡它的熟悉程度。 – Chill