使用Post方法模擬登陸爬取網頁的實現(xiàn)方法
更新時間:2017年03月27日 09:39:20 投稿:jingxian
下面小編就為大家?guī)硪黄褂肞ost方法模擬登陸爬取網頁的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
最近弄爬蟲,遇到的一個問題就是如何使用post方法模擬登陸爬取網頁。
下面是極簡版的代碼:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; public class test { //post請求地址 private static final String POST_URL = ""; //模擬谷歌瀏覽器請求 private static final String USER_AGENT = ""; //用賬號登錄某網站后 請求POST_URL鏈接獲取cookie private static final String COOKIE = ""; //用賬號登錄某網站后 請求POST_URL鏈接獲取數(shù)據(jù)包 private static final String REQUEST_DATA = ""; public static void main(String[] args) throws Exception { HashMap<String, String> map = postCapture(REQUEST_DATA); String responseCode = map.get("responseCode"); String value = map.get("value"); while(!responseCode.equals("200")){ map = postCapture(REQUEST_DATA); responseCode = map.get("responseCode"); value = map.get("value"); } //打印爬取結果 System.out.println(value); } private static HashMap<String, String> postCapture(String requestData) throws Exception{ HashMap<String, String> map = new HashMap<>(); URL url = new URL(POST_URL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setDoInput(true); // 設置輸入流采用字節(jié)流 httpConn.setDoOutput(true); // 設置輸出流采用字節(jié)流 httpConn.setUseCaches(false); //設置緩存 httpConn.setRequestMethod("POST");//POST請求 httpConn.setRequestProperty("User-Agent", USER_AGENT); httpConn.setRequestProperty("Cookie", COOKIE); PrintWriter out = new PrintWriter(new OutputStreamWriter(httpConn.getOutputStream(), "UTF-8")); out.println(requestData); out.close(); int responseCode = httpConn.getResponseCode(); StringBuffer buffer = new StringBuffer(); if (responseCode == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); httpConn.disconnect(); } map.put("responseCode", new Integer(responseCode).toString()); map.put("value", buffer.toString()); return map; } }
以上這篇使用Post方法模擬登陸爬取網頁的實現(xiàn)方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
java實現(xiàn)fibonacci數(shù)列學習示例分享(斐波那契數(shù)列)
這篇文章主要介紹了fibonacci數(shù)列(斐波那契數(shù)列)示例,大家參考使用吧2014-01-01Java并發(fā)系列之CountDownLatch源碼分析
這篇文章主要為大家詳細介紹了Java并發(fā)系列之CountDownLatch源碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03詳解使用MyBatis Generator自動創(chuàng)建代碼
這篇文章主要介紹了使用MyBatis Generator自動創(chuàng)建代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12Java中HashMap和Hashtable的區(qū)別小結
本文主要介紹了Java中HashMap和Hashtable的區(qū)別小結,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07