2010-08-12 42 views
0

我的任務是查找給定鏈接的實際新聞稿鏈接。例如說http://www.apple.com/pr/單獨標識新聞稿頁面的鏈接

我的工具必須從上述URL中單獨找到新聞稿鏈接,不包括其他廣告鏈接,在該網站中找到的標籤鏈接(或其他)。

下面的程序是開發的,其結果是給出的網頁中存在的所有鏈接。

如何修改下面的程序以從給定的URL中單獨查找新聞稿鏈接? 此外,我希望該程序是通用的,以便從任何新聞稿URL中識別新聞發佈鏈接(如果有的話)。

import java.io.*; 
import java.net.URL; 
import java.net.URLConnection; 
import java.sql.*; 
import org.jsoup.nodes.Document; 
import org.jsoup.Jsoup; 
import org.jsoup.nodes.Element; 
public class linksfind{ 
public static void main(String[] args) { 
    try{ 
     URL url = new URL("http://www.apple.com/pr/"); 
     Document document = Jsoup.parse(url, 1000); // Can also take an URL. 
     for (Element element : document.getElementsByTag("a")) { 
      System.out.println(element.attr("href"));} 
      }catch (Exception ex){ex.printStackTrace();} 
} 
} 

回答

2

看看HTML源代碼。在普通網頁瀏覽器中打開該頁面,右鍵單擊並選擇查看源代碼。您必須在HTML文檔樹中找到一個路徑來唯一標識這些鏈接。

它們全都位於<div id="releases">元素內的<ul class="stories">元素中。那麼適當的CSS選擇器將是"div#releases ul.stories a"

下面是它看起來應該像:

public static void main(String... args) throws Exception { 
    URL url = new URL("http://www.apple.com/pr/"); 
    Document document = Jsoup.parse(url, 3000); 
    for (Element element : document.select("div#releases ul.stories a")) { 
     System.out.println(element.attr("href")); 
    } 
} 

這產生截至目前,正是你想要的:

 
/pr/library/2010/07/28safari.html 
/pr/library/2010/07/27imac.html 
/pr/library/2010/07/27macpro.html 
/pr/library/2010/07/27display.html 
/pr/library/2010/07/26iphone.html 
/pr/library/2010/07/23iphonestatement.html 
/pr/library/2010/07/20results.html 
/pr/library/2010/07/19ipad.html 
/pr/library/2010/07/19alert_results.html 
/pr/library/2010/07/02appleletter.html 
/pr/library/2010/06/28iphone.html 
/pr/library/2010/06/23iphonestatement.html 
/pr/library/2010/06/22ipad.html 
/pr/library/2010/06/16iphone.html 
/pr/library/2010/06/15applestoreapp.html 
/pr/library/2010/06/15macmini.html 
/pr/library/2010/06/07iphone.html 
/pr/library/2010/06/07iads.html 
/pr/library/2010/06/07safari.html 

要了解更多關於CSS選擇器,閱讀Jsoup manualW3 CSS selector spec

+0

但是,這將適用於所有的網頁??????請指教。 我需要一些通用的解決方案。不適用於apple.com ... – LGAP 2010-08-16 14:02:06

+0

HTML解析永遠不可能是通用的。您可以最大限度地使Java代碼動態化,以便最終只需在某個配置文件中映射鏈接和選擇器即可。上司:一個問號確實足以表示一個問題。 – BalusC 2010-08-16 14:12:45

4

我不認爲會有任何明確的方式來實現這一點。您可以創建一組所有可能的關鍵字,例如'press','release'和'pr'等,並匹配url以使用正則表達式來查找關鍵字等。這些關鍵字的正確性取決於您的關鍵字的集合程度。

+0

你的意思是說要搜索網站中找到的關鍵字並選擇它們的網址嗎? – LGAP 2010-08-12 14:32:20

+0

是的。關鍵字或關鍵字的組合 – Gopi 2010-08-12 14:44:12

+0

你沒有利用Jsoup的權力。 – BalusC 2010-08-13 19:14:20

3

今天看網站。緩存到一個文件,無論你看到的鏈接。明天看看這個網站;任何新的鏈接都可以鏈接到新聞文章,也許?你會得到不正確的結果 - 一次 - 他們隨時更改你周圍的其他頁面。

您可以使用提供的RSS供稿,該供稿旨在完成您要求的內容。

+0

上午在這個任務的非RSS提要頁面的任務...因此,找到解決方案的問題... 你的寶貴意見,歡迎...如果有的話.. – LGAP 2010-08-12 14:34:08

+1

@Anand,那麼,在這種情況下,創建自己的網站,並備份RSS源,然後解析網站。如果您選擇同時編寫知識檢索引擎和推理引擎,則解決方案會更加困難。 – 2010-08-12 14:48:34

2

您需要找到一些定義「新聞稿鏈接」的屬性。在該網站的情況下,指向「/ pr/library /」表示它是Apple新聞稿。