使用Post方法模拟登陆爬取网页的实现方法
程序员文章站
2024-03-04 12:52:53
最近弄爬虫,遇到的一个问题就是如何使用post方法模拟登陆爬取网页。
下面是极简版的代码:
import java.io.bufferedreader;...
最近弄爬虫,遇到的一个问题就是如何使用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<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); // 设置输入流采用字节流 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方法模拟登陆爬取网页的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。