htmlunit最具有参考意义项目
### 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最具有参考意义项目的更多相关文章
- 项目开发中的一些注意事项以及技巧总结 基于Repository模式设计项目架构—你可以参考的项目架构设计 Asp.Net Core中使用RSA加密 EF Core中的多对多映射如何实现? asp.net core下的如何给网站做安全设置 获取服务端https证书 Js异常捕获
项目开发中的一些注意事项以及技巧总结 1.jquery采用ajax向后端请求时,MVC框架并不能返回View的数据,也就是一般我们使用View().PartialView()等,只能返回json以 ...
- Hbase运维参考(项目)
1 Hbase日常运维 1.1 监控Hbase运行状况 1.1.1 操作系统 1.1.1.1 IO 群集网络IO,磁盘IO,HDFS IO IO越大说明文件读写操作越多.当IO突然增加时,有可能:1. ...
- 基于Repository模式设计项目架构—你可以参考的项目架构设计
关于Repository模式,直接百度查就可以了,其来源是<企业应用架构模式>.我们新建一个Infrastructure文件夹,这里就是基础设施部分,EF Core的上下文类以及Repos ...
- 一个很有参考意义的unity博客
http://blog.csdn.net/lyh916/article/details/45133101
- [转]C,C++开源项目中的100个Bugs
[转]C,C++开源项目中的100个Bugs http://tonybai.com/2013/04/10/100-bugs-in-c-cpp-opensource-projects/ 俄罗斯OOO P ...
- 又见angular----步一步做一个angular4小项目
这两天看了看angular4的文档,发现他和angular1.X的差别真的是太大了,官方给出的那个管理英雄的Demo是一个非常好的入门项目,这里给出一个管理个人计划的小项目,从头至尾一步一步讲解如何去 ...
- C++框架_之Qt的开始部分_概述_安装_创建项目_快捷键等一系列注意细节
C++框架_之Qt的开始部分_概述_安装_创建项目_快捷键等一系列注意细节 1.Qt概述 1.1 什么是Qt Qt是一个跨平台的C++图形用户界面应用程序框架.它为应用程序开发者提供建立艺术级图形界面 ...
- 再遇angular(angular4项目实战指南)
这两天看了看angular4的文档,发现他和angular1.X的差别真的是太大了,官方给出的那个管理英雄的Demo是一个非常好的入门项目,这里给出一个管理个人计划的小项目,从头至尾一步一步讲解如何去 ...
- 开源项目商业模式分析(2) - 持续维护的重要性 - Selenium和WatiN
该系列第一篇发布后收到不少反馈,包括: 第一篇里说的MonicaHQ不一定盈利 没错,但是问题在于绝大多数开源项目商业数据并没有公开,从而无法判断其具体是否盈利.难得MonicaHQ是公开的,所以才用 ...
随机推荐
- freeMarker(十二)——模板语言补充知识
学习笔记,选自freeMarker中文文档,译自 Email: ddekany at users.sourceforge.net 1.特殊变量参考 特殊变量是由FreeMarker引擎自己定义的变量. ...
- FEC之我见二
前面简单说了一下FEC,以及它的配合使用的方法.下面我想详细说一下FEC算法: 曾经有位大神在帖子里这么写着:采用改进型的vandermonde矩阵RS算法.其优点算法运算复杂度更低且解决了利用矩阵构 ...
- LOJ2722 「NOI2018」情报中心
「NOI2018」情报中心 题目描述 C 国和D 国近年来战火纷飞. 最近,C 国成功地渗透进入了D 国的一个城市.这个城市可以抽象成一张有$n$ 个节点,节点之间由$n - 1$ 条双向的边连接的无 ...
- bzoj 2460: 元素 线性基
题目大意: http://www.lydsy.com/JudgeOnline/problem.php?id=2460 题解: RT 线性基裸题 #include <cstdio> #inc ...
- 2018.10.30 一题 洛谷4660/bzoj1168 [BalticOI 2008]手套——思路!问题转化与抽象!+单调栈
题目:https://www.luogu.org/problemnew/show/P4660 https://www.lydsy.com/JudgeOnline/problem.php?id=1168 ...
- 51nod 1486 大大走格子——容斥
题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1486 已知起点到某个障碍点左上角的所有点的不经过障碍的方案数,枚举 ...
- bzoj 3996 线性代数 —— 最大权闭合子图
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3996 把题中的式子拆开看看,发现就是如下关系: 如果 a[i] == 1 && ...
- 快速排序的JavaScript实现
思想 分治的思想,将原始数组分为较小的数组(但没有像归并排序一样将它们分隔开). 主元选择: 从数组中任意选择一项作为主元,通常为数组的第一项,即arr[i]:或数组的中间项, arr[Math.fl ...
- 【转】 Pro Android学习笔记(五十):ActionBar(3):搜索条
目录(?)[-] ActionBar中的搜索条 通过Menu item上定义search view 进行Searchable的配置 在activity中将search view关联searchable ...
- 【转】Pro Android学习笔记(十八):用户界面和控制(6):Adapter和AdapterView
目录(?)[-] SimpleCursorAdapter 系统预置的layout ArrayAdapter 动态数据增插删排序 自定义TextView风格 其他Adapter AdapterView不 ...