pom.xml引入
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.33</version>
</dependency>
通用代码(所有操作都是在这个基础上面新增的)
public static void main(String[] args) throws Exception {
// 网页链接
String url = "https://www.so.com";
// 创建webclient
WebClient webClient = new WebClient();
// JS 支持
webClient.getOptions().setJavaScriptEnabled(true);
// 取消 CSS 支持
webClient.getOptions().setCssEnabled(false);
// 获取指定网页实体
HtmlPage page = (HtmlPage) webClient.getPage(url);
// 获取到网页之后,进行后续的操作
}
1. input框处理
<input type="text" name="" class="" id="input">
// 获取搜索输入框
HtmlInput input = (HtmlInput) page.getHtmlElementById("input");
// 往输入框 “填值”
input.setValueAttribute("我是input框的值");
2. checkbox处理(单个)
<input id="agree" class="" type="checkbox">
// 搜索勾选框
HtmlInput checkbox = (HtmlInput) page.getHtmlElementById("agree");
// 把值给勾上
checkbox.setChecked(true);
3. a标签处理
<a href="" type="button" onclick=";" id="signBtn" class="">
点击
</a>
// 获取按钮
HtmlAnchor anchor = (HtmlAnchor) page.getByXPath("//*[@id=\"signBtn\"]").get(0);
// 点击,page2为点击之后的页面
HtmlPage page2 = anchor.click();
4. 按钮处理
<input type="submit" id="button" class="" value="">
// 获取搜索按钮
HtmlInput btn = (HtmlInput) page.getHtmlElementById("button");
// 点击,page2为点击之后的页面
HtmlPage page2 = btn.click();