Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlUnit accessing an element without id or Name

How can I access this element:

<input type="submit" value="Save as XML" onclick="some code goes here">

More info: I have to access programmatically a web page and simulate clicking on a button on it, which then will generate a xml file which I hope to be able to save on the local machine.
I am trying to do so by using HtmlUnit libraries, but all examples I could find use getElementById() or getElementByName() methods. Unfortunately, this exact element doesn't have a name or Id, so I failed miserably. I supposed then that the thing I have to do is use the getByXPath() method but I got completely lost into XPath documentation(this matter is all new to me).
I have been stuck on this for a couple of hours so I really need all the help I can get.
Thanks in advance.

like image 840
Nikola Kolev Avatar asked Dec 21 '22 20:12

Nikola Kolev


1 Answers

There are several options for an XPATH to select that input element.

Below is one option, which looks throughout the document for an input element that has an attribute named type with the value "submit" and an attribute named value with the value "Save as XML".

//input[@type='submit' and @value='Save as XML']

If you could provide a little bit more structure, a more specific (and efficient) XPATH could be created. For instance, something like this might work:

/html/body//form//input[@type='submit' and @value='Save as XML']

You should be able to use the XPATH with code like this:

client = new WebClient(BrowserVersion.FIREFOX_3)
client.javaScriptEnabled = false

page = client.getPage(url)

submitButton = page.getByXPath("/html/body//form//input[@type='submit' and @value='Save as XML']")
like image 76
Mads Hansen Avatar answered Dec 24 '22 10:12

Mads Hansen