jsoup学习整理(模拟登陆,乱码问题)

本文介绍如何使用jsoup进行模拟登录操作,并详细解释了如何处理无验证码或有漏洞可绕过的登录过程,同时提供了针对中文字符编码问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习至jsoup中文网http://www.open-open.com/jsoup/


获取cookies(针对没有验证码或者有漏洞绕过验证的模拟登陆)【例如正方教务】

Response res=null;

        res=Jsoup.connect(urlCookies)//要请求的链接

       .followRedirects(false)//不处理自动重定向

.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0")//伪装浏览器
.data("TextBox1",username)//设置请求时需要的数据
.data("TextBox2",password)
.data("Button1","")
.data("RadioButtonList1","学生")
.data("__VIEWSTATE","dDwxMTE4MjQwNDc1Ozs+MzFt0h81g6NGHTq1L9P2NfWUGLA=")
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")//设置请求头
.header("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
.header("Accept-Encoding", "gzip, deflate")
.header("Connection","keep-alive")
.header("Upgrade-Insecure-Requests", "1")

.execute();

        cookies=res.cookies();

-------------------------------------------------------------

得到cookies后这样就可以去得到页面的document对象了

elemts=Jsoup.connect(urlSource+username)
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0")
//.header("Referer", "http://172.16.1.8/default2.aspx")
.cookies(cookies)

.get();

----------------------------------------------------------------

这里有个东西说下有些网站有设置Referer,这个时候你就要填写发出请求的页面

且jsoup的Jsoup.connect是无法设置编码 的所以可能会乱码

一般情况下得到document取得elemt后new String(gt.text().getBytes("ISO8859-1"),"GBK")

转码就ok了但是有一次遇见一些偏僻的中文就不行(可能我的版本低了没设置编码功能)

最后找到了处理方法:

URL url = new URL(ppx.toString());//ppx是要访问的链接
HttpURLConnection connection = (HttpURLConnection)url.openConnection();//这里只是创建一个链接实例并没有真实网络链接
connection.setRequestMethod("GET");
//connection.addRequestProperty("ddlXQ", "1");
connection.addRequestProperty("Connection", "keep-alive");
connection.addRequestProperty("Upgrade-Insecure-Requests", "1");
connection.addRequestProperty("Host", "61.142.33.204");
connection.addRequestProperty("Referer", "http://61.142.33.204/xs_main.aspx?xh="+username);
connection.addRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*;q=0.8");
connection.addRequestProperty("Cookie", "ASP.NET_SessionId="+cookies.get("ASP.NET_SessionId"));

elemts = Jsoup.parse(connection.getInputStream(), "GBK", ppx.toString());//这个方法才去访问链接并可以设置编码

这样就算是生僻字也没问题了

Jsoup+httpclient 模拟登陆和抓取页面 package com.app.html; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.app.comom.FileUtil; public class HttpClientHtml { private static final String SITE = "login.goodjobs.cn"; private static final int PORT = 80; private static final String loginAction = "/index.php/action/UserLogin"; private static final String forwardURL = "http://user.goodjobs.cn/dispatcher.php/module/Personal/?skip_fill=1"; private static final String toUrl = "d:\\test\\"; private static final String css = "http://user.goodjobs.cn/personal.css"; private static final String Img = "http://user.goodjobs.cn/images"; private static final String _JS = "http://user.goodjobs.cn/scripts/fValidate/fValidate.one.js"; /** * 模拟等录 * @param LOGON_SITE * @param LOGON_PORT * @param login_Action * @param params * @throws Exception */ private static HttpClient loginHtml(String LOGON_SITE, int LOGON_PORT,String login_Action,String ...params) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT); // 模拟登录页面 PostMethod post = new PostMethod(login_Action); NameValuePair userName = new NameValuePair("memberName",params[0] ); NameValuePair password = new NameValuePair("password",params[1] ); post.setRequestBody(new NameValuePair[] { userName, password }); client.executeMethod(post); post.releaseConnection(); // 查看cookie信息 CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); if (cookies != null) if (cookies.length == 0) { System.out.println("Cookies is not Exists "); } else { for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].toString()); } } return client; } /** * 模拟等录 后获取所需要的页面 * @param client * @param newUrl * @throws Exception */ private static String createHtml(HttpClient client, String newUrl) throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String filePath = toUrl + format.format(new Date() )+ "_" + 1 + ".html"; PostMethod post = new PostMethod(newUrl); client.executeMethod(post); //设置编码 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK"); String content= post.getResponseBodyAsString(); FileUtil.write(content, filePath); System.out.println("\n写入文件成功!"); post.releaseConnection(); return filePath; } /** * 解析html代码 * @param filePath * @param random * @return */ private static String JsoupFile(String filePath, int random) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); File infile = new File(filePath); String url = toUrl + format.format(new Date()) + "_new_" + random+ ".html"; try { File outFile = new File(url); Document doc = Jsoup.parse(infile, "GBK"); String html="<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>"; StringBuffer sb = new StringBuffer(); sb.append(html).append("\n"); sb.append("<html>").append("\n"); sb.append("<head>").append("\n"); sb.append("<title>欢迎使用新安人才网个人专区</title>").append("\n"); Elements meta = doc.getElementsByTag("meta"); sb.append(meta.toString()).append("\n"); ////////////////////////////body////////////////////////// Elements body = doc.getElementsByTag("body"); ////////////////////////////link////////////////////////// Elements links = doc.select("link");//对link标签有href的路径都作处理 for (Element link : links) { String hrefAttr = link.attr("href"); if (hrefAttr.contains("/personal.css")) { hrefAttr = hrefAttr.replace("/personal.css",css); Element hrefVal=link.attr("href", hrefAttr);//修改href的属性值 sb.append(hrefVal.toString()).append("\n"); } } ////////////////////////////script////////////////////////// Elements scripts = doc.select("script");//对script标签 for (Element js : scripts) { String jsrc = js.attr("src"); if (jsrc.contains("/fValidate.one.js")) { String oldJS="/scripts/fValidate/fValidate.one.js";//之前的css jsrc = jsrc.replace(oldJS,_JS); Element val=js.attr("src", jsrc);//修改href的属性值 sb.append(val.toString()).append("\n").append("</head>"); } } ////////////////////////////script////////////////////////// Elements tags = body.select("*");//对所有标签有src的路径都作处理 for (Element tag : tags) { String src = tag.attr("src"); if (src.contains("/images")) { src = src.replace("/images",Img); tag.attr("src", src);//修改src的属性值 } } sb.append(body.toString()); sb.append("</html>"); BufferedReader in = new BufferedReader(new FileReader(infile)); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), "gbk")); String content = sb.toString(); out.write(content); in.close(); System.out.println("页面已经爬完"); out.close(); } catch (IOException e) { e.printStackTrace(); } return url; } public static void main(String[] args) throws Exception { String [] params={"admin","admin123"}; HttpClient client = loginHtml(SITE, PORT, loginAction,params); // 访问所需的页面 String path=createHtml(client, forwardURL); System.out.println( JsoupFile(path,1)); } }
Jsoup是一款Java的HTML解析器,可以直接从URL、文件或字符串中解析HTML内容,同时也支持通过HTTP发送POST、GET请求。因此,我们可以使用Jsoup来实现Java的模拟登陆。 下面是一个简单的示例代码,演示了如何使用Jsoup模拟登陆一个网站: ```java import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class LoginDemo { public static void main(String[] args) throws IOException { String loginUrl = "http://www.example.com/login"; // 登陆页面的URL String username = "your_username"; // 用户名 String password = "your_password"; // 密码 // 1. 获取登陆页面的HTML内容 Connection.Response response = Jsoup.connect(loginUrl) .method(Connection.Method.GET) .execute(); Document loginDoc = response.parse(); // 2. 提取登陆表单中的参数 Map<String, String> formData = new HashMap<>(); formData.put("username", username); formData.put("password", password); // 还可以添加其他表单参数 loginDoc.select("input[type=hidden]").forEach(element -> { formData.put(element.attr("name"), element.attr("value")); }); // 3. 发送POST请求进行登陆 Connection.Response loginResponse = Jsoup.connect(loginUrl) .data(formData) .cookies(response.cookies()) .method(Connection.Method.POST) .execute(); // 4. 获取登陆后的响应内容 Document homeDoc = loginResponse.parse(); System.out.println(homeDoc); } } ``` 在上面的代码中,我们首先使用Jsoup发送GET请求获取登陆页面的HTML内容,然后从HTML内容中提取登陆表单中的参数,构造POST请求,并发送POST请求进行登陆。最后,我们使用Jsoup解析登陆后的响应内容,即可获取登陆后的页面内容。 需要注意的是,我们在发送POST请求时,需要将之前获取到的cookies信息添加到请求中,以保证登陆成功。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值