How do I click a javascript button with htmlunit?

给你一囗甜甜゛ 提交于 2019-11-29 11:54:28
Clyde Lobo

Try using this addOn for firefox, it records your actions and generates the HTMLUnit code for the same. may be it could help. http://code.google.com/p/htmlunitscripter/

There's nothing special about clickable images. Something like this should work:

button = page.getHtmlElementById( "1537385" ) ;
page = button.click() ;

HtmlUnit will then run the Javascript and return the updated page.

If the id attribute of the 'a' tag isn't constant, you may need to use XPath to grab it.

I have a very similar link on one of my pages. If you can call .click() on any HtmlElement, it should be able to run associated Javascript. Here is my code (generated from HtmlUnitScripter):

HtmlElement element4 = null;
Iterable<HtmlElement> iterable5 = page.getAllHtmlChildElements();
Iterator<HtmlElement> i6 = iterable5.iterator();
while(i6.hasNext())
{
    HtmlElement anElement = i6.next();
    if(anElement instanceof HtmlImage)
    {
        HtmlImage input = (HtmlImage) anElement;
        String[] elements = "http://example.com/pages/powerbutton.png".split( "/" );

        if(input.getSrcAttribute().indexOf(elements[elements.length-1] )> -1 )
        {
            element4 = input;
            break;
        }
    }
}

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