如何在Java中將網頁內容讀取到字串中?


您可以使用多種方法在Java中讀取網頁內容。在這裡,我們將討論其中的三種。

使用openStream()方法

java.net包中的**URL**類表示統一資源定位符,用於指向全球資訊網中的資源(檔案或目錄或引用)。

此類的**openStream()**方法開啟與當前物件表示的URL的連線,並返回一個InputStream物件,您可以使用該物件從URL讀取資料。

因此,要從網頁讀取資料(使用URL類) -

  • 透過將所需網頁的URL作為引數傳遞給其建構函式來例項化java.net.URL類。

  • 呼叫openStream()方法並檢索InputStream物件。

  • 透過將上面檢索到的InputStream物件作為引數來例項化Scanner類。

示例

import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class ReadingWebPage {
   public static void main(String args[]) throws IOException {
      //Instantiating the URL class
      URL url = new URL("http://www.something.com/");
      //Retrieving the contents of the specified page
      Scanner sc = new Scanner(url.openStream());
      //Instantiating the StringBuffer class to hold the result
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(sc.next());
         //System.out.println(sc.next());
      }
      //Retrieving the String from the String Buffer object
      String result = sb.toString();
      System.out.println(result);
      //Removing the HTML tags
      result = result.replaceAll("<[^>]*>", "");
      System.out.println("Contents of the web page: "+result);
   }
}

輸出

<html><body><h1>Itworks!</h1></body></html>
Contents of the web page: Itworks!

使用HttpClient

Http客戶端是一個傳輸庫,它位於客戶端,傳送和接收HTTP訊息。它提供最新的、功能豐富的和高效的實現,滿足最新的HTTP標準。

GET請求(Http協議)用於使用給定的URI從給定的伺服器檢索資訊。使用GET的請求應該只檢索資料,並且不應該對資料產生其他影響。

HttpClient API提供了一個名為HttpGet的類,它表示get請求方法。要執行GET請求並檢索網頁的內容 -

  • HttpClients類的**createDefault()**方法返回一個CloseableHttpClient物件,它是HttpClient介面的基本實現。使用此方法,建立一個HttpClient物件。

  • 透過例項化HttpGet類來建立一個HTTP GET請求。此類的建構函式接受一個字串值,該值表示您需要向其傳送請求的網頁的URI。

  • 透過呼叫**execute()**方法執行HttpGet請求。

  • 從響應中檢索表示網站內容的InputStream物件,如下所示:

httpresponse.getEntity().getContent()

示例

import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpClientExample {
   public static void main(String args[]) throws Exception{
      //Creating a HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();
      //Creating a HttpGet object
      HttpGet httpget = new HttpGet("http://www.something.com/");
      //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);
      Scanner sc = new Scanner(httpresponse.getEntity().getContent());
      //Instantiating the StringBuffer class to hold the result
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(sc.next());
         //System.out.println(sc.next());
      }
      //Retrieving the String from the String Buffer object
      String result = sb.toString();
      System.out.println(result);
      //Removing the HTML tags
      result = result.replaceAll("<[^>]*>", "");
      System.out.println("Contents of the web page: "+result);
   }
}

輸出

<html><body><h1>Itworks!</h1></body></html>
Contents of the web page: Itworks!

使用Jsoup庫

Jsoup是一個基於Java的庫,用於處理基於HTML的內容。它提供了一個非常方便的API來提取和操作資料,使用DOM、CSS和類似jquery的方法的優點。它實現了WHATWG HTML5規範,並將HTML解析為與現代瀏覽器相同的DOM。

要使用Jsoup庫檢索網頁的內容 -

  • Jsoup類的**connect()**方法接受網頁的URL,連線到指定的網頁並返回連線物件。使用**connect()**方法連線到所需的網頁。

  • Connection介面的get()方法傳送/執行GET請求,並將HTML文件作為Document類的物件返回。透過呼叫get()方法向頁面傳送GET請求。

  • 將獲得的文件的內容檢索到字串中,如下所示:

String result = doc.body().text();

示例

import java.io.IOException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class JsoupExample {
   public static void main(String args[]) throws IOException {
      String page = "http://www.something.com/";
      //Connecting to the web page
      Connection conn = Jsoup.connect(page);
      //executing the get request
      Document doc = conn.get();
      //Retrieving the contents (body) of the web page
      String result = doc.body().text();
      System.out.println(result);
   }
}

輸出

It works!

更新於:2019年10月10日

12K+ 次瀏覽

啟動你的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.