XPath _relative_ for a given element in HTMLUnit / Groovy?

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

I read here: http://www.w3schools.com/xpath/default.asp

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

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

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!!!

+3
source share
2 answers

From the definition of the problem, it is not clear what is the element against which XPath expressions are evaluated. Assuming this is a node document, the following XPath expressions will select the desired node:

   */*/div[@class='levelone']

   html/body/div[@class='levelone']

   descendant::div[@class='levelone']

, XML- ( ) . / XPath- ( groovy) , :

   */*/x:div[@class='levelone']

   x:html/x:body/x:div[@class='levelone']

   descendant::x:div[@class='levelone']
+2

. -, , (doh)

#!/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']")
assert element.size()==1

Doh!

!

0

Source: https://habr.com/ru/post/1748667/


All Articles