java HtmlUnit 访问没有 id 或 Name 的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4334155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HtmlUnit accessing an element without id or Name
提问by Nikola Kolev
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 HtmlUnitlibraries, 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.
更多信息:我必须以编程方式访问网页并模拟单击其上的按钮,然后将生成一个 xml 文件,我希望能够将其保存在本地计算机上。
我试图通过使用HtmlUnit库来做到这一点,但我能找到的所有示例都使用getElementById()或getElementByName()方法。不幸的是,这个确切的元素没有名称或 ID,所以我很惨地失败了。我当时认为我必须做的事情是使用getByXPath()方法,但我完全迷失在 XPath 文档中(这对我来说是全新的)。
我已经坚持了几个小时,所以我真的需要我能得到的所有帮助。
提前致谢。
回答by Mads Hansen
There are several options for an XPATH to select that input
element.
XPATH 有多个选项可以选择该input
元素。
Below is one option, which looks throughout the document for an input
element that has an attribute named typewith the value "submit" and an attribute named valuewith the value "Save as XML".
下面是一个选项,它在整个文档中查找input
具有名为type且值为“submit”的属性和名为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:
如果您可以提供更多的结构,则可以创建更具体(和有效)的 XPATH。例如,这样的事情可能会奏效:
/html/body//form//input[@type='submit' and @value='Save as XML']
You should be able to use the XPATH with code like this:
您应该能够将 XPATH 与如下代码一起使用:
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']")
回答by Mosty Mostacho
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:
尽管在大多数情况下我会推荐使用 XPath,但如果您对此一无所知,您可以尝试getInputByValue(String value)方法。这是基于您的问题的示例:
// 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());