Java Reference
In-Depth Information
names: for the
HTML
element “a”, the class is
HtmlAnchor
; for “h1”, the class is
HtmlHeading1
.
12.3.9
Using XPath
Use
XP
ath
3
for complex searches to reduce test code complexity.
XP
ath is a language
specified by the
W3C
for querying nodes in an
XML
document. We won't cover the
XP
ath language itself here; we focus on its usage in HtmlUnit to perform two types of
tasks: getting to a specific element and gathering data.
A
CCESSING
ELEMENTS
WITH
XP
ATH
You call one of two methods to run an
XP
ath query:
getByXPath
returns a list of ele-
ments and
getFirstByXPath
returns a single element. Because
DomNode
implements
both methods, it's accessible not only to HtmlPage but to all
DomNode
subclasses,
which include the
HTML
classes.
Knowing which
XP
ath expression to use can involve a lot of trial and error. Fortu-
nately, you can inspect any website with
XP
ath Checker
4
or Firebug,
5
free open source
Firefox add-ons, and create an
XP
ath from the current selection. For example, to
access the text input field on Google's home page, use
/html/body/center/form/
table/tbody/tr/td[2]/input[2]
.
Note that expressions generated automatically from such tools usually suffer from
the same indexing issue we discussed earlier in section 12.3.7 “Accessing elements by
name versus index.” By inspecting the code, you can create the following expression,
which is more resilient to changes in the page:
//input[@name='q']
We all know there's no such thing as a free lunch,
6
and this expression's gain in page-
change resilience and brevity comes with a small performance price:
XP
ath must find
all input elements on the page that match the criteria
[@name='q']
and then give us
the first one. This is in contrast to the first expression, which drills down to a known
spot in the page or fails along the way if an element is missing. To run this
XP
ath
query, the call is
page.getFirstByXPath("//input[@name='q']");
We look next at a powerful
XP
ath feature supported by the HtmlUnit
API
: the ability
to collect data.
D
ATA
GATHERING
WITH
XP
ATH
An extremely powerful feature of
XP
ath is its ability to return a set of nodes. This fea-
ture allows us to perform, with one expression, a query that returns a data set. This is
3
XPath 1.0:
http://www.w3.org/TR/xpath
4
XPath Checker:
http://slesinsky.org/brian/code/xpath_checker.html
5
Firebug:
http://getfirebug.com/
6
TANSTAAFL:
http://en.wikipedia.org/wiki/TANSTAAFL