HtmlUnit accessing an element without id or Name

混江龙づ霸主 提交于 2019-12-05 01:02:14

问题


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.


回答1:


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



回答2:


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());


来源:https://stackoverflow.com/questions/4334155/htmlunit-accessing-an-element-without-id-or-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!