### HtmlUnit What?

- 项目1 https://gitee.com/dgwcode/spiderTmallTradeInfo

- 项目2 https://gitee.com/dgwcode/SimulationFang

这两个项目,是最新Htmlunit包下的新项目,很多东西在国内博客,百度,技术网站都找不到例子,有时间可以看看。

Introduction

The dependencies page lists all the jars that you will need to have in your classpath.

The class com.gargoylesoftware.htmlunit.WebClient is the main starting point. This simulates a web browser and will be used to execute all of the tests.

Most unit testing will be done within a framework like JUnit so all the examples here will assume that we are using that.

In the first sample, we create the web client and have it load the homepage from the HtmlUnit website. We then verify that this page has the correct title. Note that getPage() can return different types of pages based on the content type of the returned data. In this case we are expecting a content type of text/html so we cast the result to an com.gargoylesoftware.htmlunit.html.HtmlPage.

@Test
public void homePage() throws Exception {
try (final WebClient webClient = new WebClient()) {
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
Assert.assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText()); final String pageAsXml = page.asXml();
Assert.assertTrue(pageAsXml.contains("<body class=\"composite\">")); final String pageAsText = page.asText();
Assert.assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
}
}

Submitting a form

Frequently we want to change values in a form and submit the form back to the server. The following example shows how you might do this.

@Test
public void submittingForm() throws Exception {
try (final WebClient webClient = new WebClient()) { // Get the first page
final HtmlPage page1 = webClient.getPage("http://some_url"); // Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
final HtmlForm form = page1.getFormByName("myform"); final HtmlSubmitInput button = form.getInputByName("submitbutton");
final HtmlTextInput textField = form.getInputByName("userid"); // Change the value of the text field
textField.type("root"); // Now submit the form by clicking the button and get back the second page.
final HtmlPage page2 = button.click();
}
}

Imitating a specific browser

Often you will want to simulate a specific browser. This is done by passing a com.gargoylesoftware.htmlunit.BrowserVersion into the WebClient constructor. Constants have been provided for some common browsers but you can create your own specific version by instantiating a BrowserVersion.

@Test
public void homePage_Firefox() throws Exception {
try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52)) {
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
Assert.assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
}
}

Specifying this BrowserVersion will change the user agent header that is sent up to the server and will change the behavior of some of the JavaScript.

Finding a specific element

Once you have a reference to an HtmlPage, you can search for a specific HtmlElement by one of 'get' methods, or by using XPath or CSS selectors.

Traversing the DOM tree

Below is an example of finding a 'div' by an ID, and getting an anchor by name:

@Test
public void getElements() throws Exception {
try (final WebClient webClient = new WebClient()) {
final HtmlPage page = webClient.getPage("http://some_url");
final HtmlDivision div = page.getHtmlElementById("some_div_id");
final HtmlAnchor anchor = page.getAnchorByName("anchor_name");
}
}

A simple way for finding elements might be to find all elements of a specific type.

 @Test
public void getElements() throws Exception {
try (final WebClient webClient = new WebClient()) {
final HtmlPage page = webClient.getPage("http://some_url");
NodeList inputs = page.getElementsByTagName("input");
final Iterator<E> nodesIterator = nodes.iterator();
// now iterate
}
}

There is rich set of methods usable to locate page elements e.g.

  • HtmlPage.getAnchors(); HtmlPage.getAnchorByHref(String); HtmlPage.getAnchorByName(String); HtmlPage.getAnchorByText(String)
  • HtmlPage.getElementById(String); HtmlPage.getElementsById(String); HtmlPage.getElementsByIdAndOrName(String);
  • HtmlPage.getElementByName(String); HtmlPage.getElementsByName(String)
  • HtmlPage.getFormByName(String); HtmlPage.getForms()
  • HtmlPage.getFrameByName(String); HtmlPage.getFrames()

You can also start searching from the document element (HtmlPage.getDocumentElement()) and then traverse the dom tree

  • HtmlElement.getElementsByAttribute(String, String, String)
  • DomElement.getElementsByTagName(String); DomElement.getElementsByTagNameNS(String, String)
  • DomElement.getChildElements(); DomElement.getChildElementCount()
  • DomElement.getFirstElementChild(); DomElement.getLastElementChild()
  • HtmlElement.getEnclosingElement(String); HtmlElement.getEnclosingForm()
  • DomNode.getChildNodes(); DomNode.getChildren(); DomNode.getDescendants(); DomNode.getDomElementDescendants(); DomNode.getFirstChild(); DomNode.getHtmlElementDescendants() DomNode.getLastChild(); DomNode.getNextElementSibling(); DomNode.getNextSibling(); DomNode.getPreviousElementSibling(); getPreviousSibling()

XPath queries

XPath is the suggested way for more complex searches, a brief tutorial can be found in W3Schools

@Test
public void xpath() throws Exception {
try (final WebClient webClient = new WebClient()) {
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net"); //get list of all divs
final List<?> divs = page.getByXPath("//div"); //get div which has a 'name' attribute of 'John'
final HtmlDivision div = (HtmlDivision) page.getByXPath("//div[@name='John']").get(0);
}
}

CSS Selectors

You can also use CSS selectors

@Test
public void cssSelector() throws Exception {
try (final WebClient webClient = new WebClient()) {
final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net"); //get list of all divs
final DomNodeList<DomNode> divs = page.querySelectorAll("div");
for (DomNode div : divs) {
....
} //get div which has the id 'breadcrumbs'
final DomNode div = page.querySelector("div#breadcrumbs");
}
}

Using a proxy server

The last WebClient constructor allows you to specify proxy server information in those cases where you need to connect through one.

@Test
public void homePage_proxy() throws Exception {
try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52, "myproxyserver", myProxyPort)) { //set proxy username and password
final DefaultCredentialsProvider credentialsProvider = (DefaultCredentialsProvider) webClient.getCredentialsProvider();
credentialsProvider.addCredentials("username", "password"); final HtmlPage page = webClient.getPage("http://htmlunit.sourceforge.net");
Assert.assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
}
}

Specifying this BrowserVersion will change the user agent header that is sent up to the server and will change the behavior of some of the JavaScript.

htmlunit最具有参考意义项目的更多相关文章

  1. 项目开发中的一些注意事项以及技巧总结 基于Repository模式设计项目架构—你可以参考的项目架构设计 Asp.Net Core中使用RSA加密 EF Core中的多对多映射如何实现? asp.net core下的如何给网站做安全设置 获取服务端https证书 Js异常捕获

    项目开发中的一些注意事项以及技巧总结   1.jquery采用ajax向后端请求时,MVC框架并不能返回View的数据,也就是一般我们使用View().PartialView()等,只能返回json以 ...

  2. Hbase运维参考(项目)

    1 Hbase日常运维 1.1 监控Hbase运行状况 1.1.1 操作系统 1.1.1.1 IO 群集网络IO,磁盘IO,HDFS IO IO越大说明文件读写操作越多.当IO突然增加时,有可能:1. ...

  3. 基于Repository模式设计项目架构—你可以参考的项目架构设计

    关于Repository模式,直接百度查就可以了,其来源是<企业应用架构模式>.我们新建一个Infrastructure文件夹,这里就是基础设施部分,EF Core的上下文类以及Repos ...

  4. 一个很有参考意义的unity博客

    http://blog.csdn.net/lyh916/article/details/45133101

  5. [转]C,C++开源项目中的100个Bugs

    [转]C,C++开源项目中的100个Bugs http://tonybai.com/2013/04/10/100-bugs-in-c-cpp-opensource-projects/ 俄罗斯OOO P ...

  6. 又见angular----步一步做一个angular4小项目

    这两天看了看angular4的文档,发现他和angular1.X的差别真的是太大了,官方给出的那个管理英雄的Demo是一个非常好的入门项目,这里给出一个管理个人计划的小项目,从头至尾一步一步讲解如何去 ...

  7. C++框架_之Qt的开始部分_概述_安装_创建项目_快捷键等一系列注意细节

    C++框架_之Qt的开始部分_概述_安装_创建项目_快捷键等一系列注意细节 1.Qt概述 1.1 什么是Qt Qt是一个跨平台的C++图形用户界面应用程序框架.它为应用程序开发者提供建立艺术级图形界面 ...

  8. 再遇angular(angular4项目实战指南)

    这两天看了看angular4的文档,发现他和angular1.X的差别真的是太大了,官方给出的那个管理英雄的Demo是一个非常好的入门项目,这里给出一个管理个人计划的小项目,从头至尾一步一步讲解如何去 ...

  9. 开源项目商业模式分析(2) - 持续维护的重要性 - Selenium和WatiN

    该系列第一篇发布后收到不少反馈,包括: 第一篇里说的MonicaHQ不一定盈利 没错,但是问题在于绝大多数开源项目商业数据并没有公开,从而无法判断其具体是否盈利.难得MonicaHQ是公开的,所以才用 ...

随机推荐

  1. Cannot resolve class or package 'springframework' less... (Ctrl+F1) Inspection info:Spring XML mode

    其实这个问题是由于MySQL 这个jar 包依赖类型默认是runtime ,也就是说只有运行时生效,所以虽然这里报错,但是不影响你代码运行. 解决方案: 将runtime 修改为Compile 即可 ...

  2. 11g 如何添加,替换,移除,迁移 OCR ?

    一: 增加 裸设备上,创建至少280MB的裸设备,权限是640,属主是root:oinstall共享文件系统 Or NFS,创建空文件,权限是640,属主是root:oinstall root用户执行 ...

  3. CF1092 D & E —— 思路+单调栈,树的直径

    题目:https://codeforces.com/contest/1092/problem/D1 https://codeforces.com/contest/1092/problem/D2 htt ...

  4. NSDictionary和NSArray

    // 字典里套数组 NSArray *array1 = @[@"huahau" , @"hehe"]; NSArray *array2 = @[@"x ...

  5. GPIO编程1:用文件IO的方式操作GPIO

    概述 通过 sysfs 方式控制 GPIO,先访问 /sys/class/gpio 目录,向 export 文件写入 GPIO 编号,使得该 GPIO 的操作接口从内核空间暴露到用户空间,GPIO 的 ...

  6. 2006浙大火星A+B

    题目描述:     读入两个不超过25位的火星正整数A和B,计算A+B.需要注意的是:在火星上,整数不是单一进制的,第n位的进制就是第n个素数.例如:地球上的10进制数2,在火星上记为“1,0”,因为 ...

  7. ubuntu dd烧录镜像文件

    df命令查看挂在的U盘和硬盘,ssd 右边可以看到路径 sudo dd if=cn_windows_10_multiple_editions_version_1703_updated_july_201 ...

  8. samba server导出/datasmb/目录;samba client挂载/data/至本地的/mydata目录;本地的mysqld或mariadb服务的数据目录设置为/mydata, 要求服务能正常启动,且可正常 存储数据;

    实验环境:CentOS7 主机(mini2) :172.16.250.247  主机名::localhost 客户端(mini3):172.16.253.99  主机名:pxe99 #主机:配置文件的 ...

  9. iOS使用VideoToolbox硬编码录制H264视频

    http://blog.csdn.net/shawnkong/article/details/52045894

  10. Ajax的包装

    /** * Created by Administrator on 2016/12/27. *//** * 创建XMLHttpRequest对象 * @param _method 请求方式: post ...