2011-09-01 24 views
0

我想從此URL提取內容http://www.xyz.com/default.aspx這是我想使用正則表達式提取的以下內容。在java中使用正則表達式從URL中提取一些內容

String expr = " 
What Regular Expression should I use here  
"; 

Pattern patt = Pattern.compile(expr, Pattern.DOTALL | Pattern.UNIX_LINES); 
URL url4 = null; 

try { 
    url4 = new URL("http://www.xyz.com/default.aspx");     
} catch (MalformedURLException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
System.out.println("Text" +url4); 
Matcher m = null; 
try { 
    m = patt.matcher(getURLContent(url4)); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
System.out.println("Match" +m); 

while (m.find()) { 
    String stateURL = m.group(1); 
    System.out.println("Some Data" +stateURL); 
} 

public static CharSequence getURLContent(URL url8) throws IOException { 
      URLConnection conn = url8.openConnection(); 
      String encoding = conn.getContentEncoding(); 
      if (encoding == null) { 
      encoding = "ISO-8859-1"; 
      } 
      BufferedReader br = new BufferedReader(new 
       InputStreamReader(conn.getInputStream(), encoding)); 
      StringBuilder sb = new StringBuilder(16384); 
      try { 
      String line; 
      while ((line = br.readLine()) != null) { 
       sb.append(line); 
       System.out.println(line); 
       sb.append('\n'); 
      } 
      } finally { 
      br.close(); 
      } 
      return sb; 
     } 
+5

不要使用正則表達式!嘗試像[jsoup](http://jsoup.org)。 –

+0

所以用jsoup我可以提取我想從URL中提取的任何內容?並且你可以根據我的代碼使用JSOUP做一些例子...這將不勝感激...... – ferhan

+0

看看jsoup主頁上的例子。您可以根據網頁的HTML結構提取所需的文本。 –

回答

0

作爲@ bkent314已提到的,jsoup比使用正則表達式更好的和更清潔的方法。

如果您檢查該網站的源代碼,你基本上要由這個片段內容: -

<div class="smallHd_contentTd"> 
    <div class="breadcrumb">...</div> 
    <h2>Services</h2> 
    <p>...</p> 
    <p>...</p> 
    <p>...</p> 
</div> 

使用jsoup,你的代碼可能是這個樣子: -

Document doc = Jsoup.connect("http://www.ferotech.com/Services/default.aspx").get(); 

Element content = doc.select("div.smallHd_contentTd").first(); 

String header = content.select("h2").first().text(); 

System.out.println(header); 

for (Element pTag : content.select("p")) { 
    System.out.println(pTag.text()); 
} 

希望這可以幫助。

相關問題