最近由于业务需求写了一个爬虫,但是由于asp.net中的翻页数据都是用_doPostBack表单提交的,只能获取到第一页的数据,几经周折找到了如下的解决办法:
//要扒取的网页的地址
String url = "http://nmgs.china12366.org/Search.aspx?type=3&text=%E6%97%B6%E9%97%B4";
//设置用户代理
String user_Agent="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36";
//获取登录框的隐含参数 type="hidden"
Connection connection=Jsoup.connect(url).timeout(60000);
connection.header("User-Agent", user_Agent);//配置模拟浏览器
Connection.Response response=null;
String sessionId ="";
try {
response = connection.method(Connection.Method.GET).execute();// 获取响应
sessionId = response.cookies().get("ASP.NET_SessionId");
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
// 应用JsoupHtml解析包解析html包含参数
Document doc = Jsoup.parse(response.body());// 转换为Dom树
// map存放post时的数据
Map<String, String> datas = new HashMap<>();
// 要跳转到的页数
String ddlGoto = "第2页";
Elements inputElemets = doc.select("form[method=post]").first()
.select("input[name]");
for (Iterator it = inputElemets.iterator(); it.hasNext();) {
Element inputElement = (Element) it.next();
if("__EVENTTARGET".equals(inputElement.attr("name"))){
datas.put("ddlGoto",ddlGoto);
datas.put("__EVENTTARGET", "ddlGoto");
}else{
datas.put(inputElement.attr("name"), inputElement.attr("value"));
}
}
Connection connection2 = Jsoup.connect(url).timeout(60000);
try {
// 设置cookies和要传递的参数
Map<String,String> cookies = new HashMap<>();
cookies.put("ASP.NET_SessionId",sessionId);
Connection connection1 = connection2.ignoreContentType(true)
.method(Connection.Method.POST).data(datas)
.cookies(response.cookies());
Connection.Response rs = connection1.execute();
Document document = Jsoup.parse(rs.body());
System.out.println(document);
} catch (IOException e1) {
e1.printStackTrace();
}