2017-06-21 55 views
0

因此,當我使用Java語言發送HTTP請求時,我將以HTML代碼的形式獲取響應。例如,發送請求:http://www.google.com/search?q=what%20is%20mango如何使用HTML響應來提取Java中的數據?

獲得在這個頁面的HTML代碼的形式響應: https://www.google.co.in/search?q=what+is+mango&rlz=1C1CHBF_enIN743IN743&oq=what+is+mango&aqs=chrome..69i57j0l5.4095j0j7&sourceid=chrome&ie=UTF-8

所以,從這個響應頁面,我想再次發送到維基百科頁面的請求(中所列響應頁面),然後我想約芒果內容從維基百科頁面複製和寫入到一個文件我的系統

代碼從我送了谷歌搜索請求上:

package api_test; 

import java.io.*; 
import java.net.*; 
import java.util.*; 

public class HttpURLConnectionExample { 

    private final String USER_AGENT= "Mozilla/5.0"; 

    public static void main(String[] args) throws Exception { 

     HttpURLConnectionExample http= new HttpURLConnectionExample(); 

     System.out.println("testing 1- send http get request"); 
     http.sendGet(); 

    } 

    private void sendGet() throws Exception{ 

     Scanner s= new Scanner(System.in); 
     System.out.println("enter the URL"); 
     String url = s.nextLine(); 

     URL obj = new URL("http://"+url); 
     HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 

     // optional default is GET 
     con.setRequestMethod("GET"); 

     //add request header 
     con.setRequestProperty("User-Agent", USER_AGENT); 

     int responseCode = con.getResponseCode(); 
     System.out.println("\nSending 'GET' request to URL : " + url); 
     System.out.println("Response Code : " + responseCode); 

     BufferedReader in = new BufferedReader(
       new InputStreamReader(con.getInputStream())); 
     String inputLine; 
     StringBuffer response = new StringBuffer(); 

     while ((inputLine = in.readLine()) != null) { 
      response.append(inputLine); 
     } 
     in.close(); 

     //print result 
     System.out.println(response.toString()); 
    } 

} 
+0

爲'href =「https://en.wikipedia.org/wiki/Mango」'解析文件?如果你試圖自動化這種事情,那麼也許看看像這樣的東西:http://www.seleniumhq.org/ –

+0

解析HTML的另一種選擇可能是[JSoup](https://jsoup.org /) –

+0

你應該要求一個更可管理的格式。看看[MediaWiki的API頁面](https://www.mediawiki.org/wiki/API:Main_page#The_format),特別注意'format'參數。與原始的HTML抓取相比,JSON可能會更具可管理性。 – zero298

回答

1

我認爲你需要的是一個HTML解析器,如jsoup

,如果谷歌的佈局變化很大,但現在的CSS選擇器「#搜尋h3.r一個」工作你可以做類似

Document doc = Jsoup.connect("http://www.google.com/search?q=what%20is%20mango").get(); 
Element result = doc.select("#search h3.r a").first(); 
String link = result.attr("data-href"); 

我不知道。