XPath _relative_ to given element in HTMLUnit/Groovy?

Posted by Misha Koshelev on Stack Overflow See other posts from Stack Overflow or by Misha Koshelev
Published on 2010-06-05T14:45:52Z Indexed on 2010/06/05 14:52 UTC
Read the original article Hit count: 236

Filed under:
|
|

Dear All:

I would like to evaluate an XPath expression relative to a given element.

I have been reading here: http://www.w3schools.com/xpath/default.asp

And it seems like one of the syntaxes below should work (esp no leading slash or descendant:)

However, none seem to work in HTMLUnit. Any help much appreciated (oh this is a groovy script btw). Thank you!

http://htmlunit.sourceforge.net/

http://groovy.codehaus.org/

Misha


#!/usr/bin/env groovy

import com.gargoylesoftware.htmlunit.WebClient

def html="""
<html><head><title>Test</title></head>
<body>
<div class='levelone'>
 <div class='leveltwo'>
    <div class='levelthree' />
 </div>
 <div class='leveltwo'>
    <div class='levelthree' />
    <div class='levelthree' />
 </div>
</div>

</body>
</html>
"""

def f=new File('/tmp/test.html')
if (f.exists()) {
 f.delete()
}
def fos=new FileOutputStream(f)
fos<<html

def webClient=new WebClient()
def page=webClient.getPage('file:///tmp/test.html')

def element=page.getByXPath("//div[@class='levelone']")
assert element.size()==1
element=page.getByXPath("div[@class='levelone']")
assert element.size()==0
element=page.getByXPath("/div[@class='levelone']")
assert element.size()==0
element=page.getByXPath("descendant:div[@class='levelone']") // this
gives namespace error
assert element.size()==0

Thank you!!!

© Stack Overflow or respective owner

Related posts about xpath

Related posts about groovy