使用Post方法模拟登陆爬取网页的实现方法-创新互联

创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

为灞桥等地区用户提供了全套网页设计制作服务,及灞桥网站建设行业解决方案。主营业务为网站建设、网站制作、灞桥网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

最近弄爬虫,遇到的一个问题就是如何使用post方法模拟登陆爬取网页。

下面是极简版的代码:

使用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链接获取数据包
 private static final String REQUEST_DATA = "";
 
 public static void main(String[] args) throws Exception {
  HashMap 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 postCapture(String requestData) throws Exception{
  HashMap map = new HashMap<>();
  
  URL url = new URL(POST_URL);
  HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
  httpConn.setDoInput(true); // 设置输入流采用字节流
  httpConn.setDoOutput(true); // 设置输出流采用字节流
  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方法模拟登陆爬取网页的实现方法-创新互联
当前链接:http://azwzsj.com/article/pipip.html