最近弄爬蟲,遇到的一個(gè)問題就是如何使用post方法模擬登陸爬取網(wǎng)頁。
專注于為中小企業(yè)提供做網(wǎng)站、成都網(wǎng)站制作服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)海原免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了上1000+企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
下面是極簡版的代碼:
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請(qǐng)求地址 private static final String POST_URL = ""; //模擬谷歌瀏覽器請(qǐng)求 private static final String USER_AGENT = ""; //用賬號(hào)登錄某網(wǎng)站后 請(qǐng)求POST_URL鏈接獲取cookie private static final String COOKIE = ""; //用賬號(hào)登錄某網(wǎng)站后 請(qǐng)求POST_URL鏈接獲取數(shù)據(jù)包 private static final String REQUEST_DATA = ""; public static void main(String[] args) throws Exception { HashMapmap = 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"); } //打印爬取結(jié)果 System.out.println(value); } private static HashMap postCapture(String requestData) throws Exception{ HashMap map = new HashMap<>(); URL url = new URL(POST_URL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setDoInput(true); // 設(shè)置輸入流采用字節(jié)流 httpConn.setDoOutput(true); // 設(shè)置輸出流采用字節(jié)流 httpConn.setUseCaches(false); //設(shè)置緩存 httpConn.setRequestMethod("POST");//POST請(qǐng)求 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方法模擬登陸爬取網(wǎng)頁的實(shí)現(xiàn)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持創(chuàng)新互聯(lián)。