Question

<input type="submit" class="submit-button" style="white-space:normal" value="hello world!">

This is how the HTML submit button works, in HTMLUNIT I already got the form, using the list:

HtmlForm form = this.page.getForms().get(0);

But now the site im trying to load doesn't have id or name on the submit button, just a class & a value.

I tried doing this:

HtmlButton button = (HtmlButton) page.getByXPath("/html/body//form//input[@type='submit' and @value='Hello world!']");

But when it loads, I get this error:

Exception in thread "Thread-1" java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlButton
    at Web.getButton(Web.java:78)
    at java.lang.Thread.run(Unknown Source)

How can I get button without id or value?

Was it helpful?

Solution

Just use the getInputByValue(String) method on the form:

HtmlForm form = this.page.getForms().get(0);
System.out.println(form.getInputByValue("Hello world!").asXml());

OTHER TIPS

page.getByXPath("/html/body//form//input[@type='submit' and @value='Hello world!']"); returns a List.

HtmlButton button = (HtmlButton) page.getByXPath("/html/body//form//input[@type='submit' and @value='Hello world!']"); will try to cast this List to a HtmlButton which always will cause an exception to be thrown.

If you are certain that exactly one element will always match the XPath expression, it should be safe to just pick the first (and only) element of the list:

HtmlButton button = (HtmlButton) page.getByXPath("/html/body//form//input[@type='submit' and @value='Hello world!']").get(0);

If I were you, however, I would add checks for non existing element and if the list contains more than one element.

Use this

HtmlElement input = form.getElementsByAttribute("input", "value", "hello world!").get(0);

to get the element and click the element

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top