HtmlUnit的一点使用心得

本文介绍了在项目中使用HtmlUnit库的一些关键操作,包括pom.xml的配置,通用代码基础,以及针对input框、checkbox、a标签和按钮的具体处理方法。

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

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值