版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zmh458/article/details/84501739
前言
进行爬虫的首先要做的事情就是模拟登陆你要爬虫的网站,最近小编模拟登陆了某云网站,接下来和大家分享一下。
叙述
Htmlunit概述
htmlunit 是一款开源的java 页面分析工具,读取页面后,可以有效的使用htmlunit分析页面上的内容。
项目可以模拟浏览器运行,被誉为java浏览器的开源实现。是一个没有界面的浏览器。
maven配置
<dependencies>
<!-- https://mvnrepository.com/artifact/net.sourceforge.htmlunit/htmlunit -->
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>
</dependencies>
具体的步骤
1、定义一个WebClient客户端。就相当于定义了一个没有界面的浏览器。
2、使用WebClient客户端从指定URL获取HtmlPage。HtmlPage中包含目标URL页面中的所有信息。
3、从HtmlPage中获取我们需要的指定元素。
模拟登陆代码
String loginURL = "https://www.mosoteach.cn/web/index.php?c=passport&m=index";
try {
URL urllink = new URL(loginURL);
// 模拟一个浏览器
WebClient webClient = new WebClient(BrowserVersion.CHROME);
WebRequest request = new WebRequest(urllink);
request.setAdditionalHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
webClient.getOptions().setActiveXNative(true);
webClient.setJavaScriptTimeout(30000);
// 设置webClient的相关参数
webClient.setCssErrorHandler(new SilentCssErrorHandler());
//设置ajax
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
//设置支持js
webClient.getOptions().setJavaScriptEnabled(true);
//CSS渲染禁止
webClient.getOptions().setCssEnabled(true);
//超时时间
webClient.getOptions().setTimeout(50000);
//设置js抛出异常:false
webClient.getOptions().setThrowExceptionOnScriptError(false);
//允许重定向
webClient.getOptions().setRedirectEnabled(true);
//允许cookie
webClient.getCookieManager().setCookiesEnabled(true);
// 模拟浏览器打开一个目标网址
HtmlPage page = webClient.getPage(request);
/**等待js加载完全,CSDN这点 特别坑,js加载时间超长!!!!!!! 后人切记不要用CSDN模拟登陆!!!!!!!**/
webClient.waitForBackgroundJavaScript(10000*3);
// 根据form的名字获取页面表单,也可以通过索引来获取:page.getForms().get(0)
HtmlForm form = (HtmlForm) page.getForms().get(0);
HtmlTextInput username = (HtmlTextInput) form.getInputByName("account_name");
HtmlPasswordInput password = (HtmlPasswordInput) form.getInputByName("user_password");
username.setValueAttribute("xxxx"); //用户名
password.setValueAttribute("xxxx"); //密码
HtmlButton button = (HtmlButton) page.getByXPath("//button[contains(@id, 'login-button-1')]").get(0);
HtmlPage retPage = button.click();
// 等待JS驱动dom完成获得还原后的网页
webClient.waitForBackgroundJavaScript(60000);
String webContent =retPage.asXml();
CookieManager CM = webClient.getCookieManager();
Set<Cookie> cookies = CM.getCookies()
for (Cookie c : cookies) {
System.out.print(c.getName()+":"+c.getValue());
}
webClient.close();
System.out.println("Success!");
黑色背景 |
小结
掌握学习的套路,其他的一切事情都不是事情啦。
感谢您的阅读~~