### 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. bzoj 3754: Tree之最小方差树 模拟退火+随机三分

    题目大意: 求最小方差生成树.N<=100,M<=2000,Ci<=100 题解: 首先我们知道这么一个东西: 一些数和另一个数的差的平方之和的最小值在这个数是这些数的平均值时取得 ...

  2. Windows常用的命令

    wmic msinfo32 regedit msconfig

  3. iOS重写drawRect方法实现带箭头的View

    创建一个UIView的子类,重写drawRect方法可以实现不规则形状的View,这里提供一个带箭头View的实现代码: ArrowView.h #import <UIKit/UIKit.h&g ...

  4. 安装ORACLE时在Linux上设置内核参数的含义

    前两天看到一篇Redhat官方的Oracle安装文档,对于Linux内核参数的修改描述的非常清晰. 安装Oracle之前,除了检查操作系统的硬件和软件是否满足安装需要之外,一个重点就是修改内核参数,其 ...

  5. 初识Luajit

    转自:http://www.cppblog.com/pwq1989/archive/2013/11/28/204487.html 大家可以从官网下载到源码(http://luajit.org/),也可 ...

  6. Python-IO模式介绍

    事件驱动模型:有个事件队列,把事件放到队列里,然后循环这个队列,取出事件执行 5种IO模式: 阻塞 I/O(blocking IO) 非阻塞 I/O(nonblocking IO) I/O 多路复用( ...

  7. 使用SecureCRT工具部署项目

    总结下我的Java开发过程的一些知识点: 我要上线某个项目,此时我需要给测试人员发送安全扫描文件,等待测试人员完成项目的扫描之后才可以完成上线: 1 将项目打成war包.比如implgtyy.war文 ...

  8. Material使用05 MdListModule模块 MdButtonToggleModule模块

    1 在共享模块中导入MdListModule模块 import { NgModule } from '@angular/core'; import { CommonModule } from '@an ...

  9. EPEL for CentOS or Redhat

    注:地址可能会变 RHEL/CentOS 7 64 Bit # wget http://dl.fedoraproject.org/pub/epel/beta/7/x86_64/epel-release ...

  10. 12、geo数据上传

    1.注册一个NCBI账户 注册geo账户(老用户和新用户): https://www.ncbi.nlm.nih.gov/geo/submitter/ 有3个月的时间 GEO DataSets > ...