开发者

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 g开发者_运维知识库etElementById() 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.


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']")


Although I would, in most cases, recommend using XPath, if you don't know anything about it you can try the getInputByValue(String value) method. This is an example based on your question:

// Fetch the form somehow
HtmlForm form = this.page.getForms().get(0);
// Get the input by its value
System.out.println(form.getInputByValue("Save as XML").asXml());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜