How to click javascript button using htmlunit?

I am working on an application that automatically clicks a button on a webpage using htmlunit in Java. The only problem is that this button is a javascript button, so the standard getInputByName () will not work. Any suggestions with this? The code for the button is shown below.

<a class="vote_1" id="1537385" href="/javascript%3Avoid%280%29/index"><img src="/images/parts/btn-vote.gif" alt="Btn-vote" /></a> 

In addition, a different voting code is used here.

<div id="content"><script type="text/javascript" src="/js/scriptFeeds/voteArticle.js"></script> 

Which leads to the following javascript:

var pressed = new Array();

$j(document).ready(function() {
var nr = $j("input#number_of_articles").val();
for(var i=1; i<=nr; i++){
    $j("a.vote_"+i).click(function(){
        var article   = $j(this).attr("id");
        $j('#'+article).hide();
        if (!pressed[article]) {
            pressed[article] = "yes";
            jQuery.post('/vote-article', {
                _token: $j("#_token").val(),
                article_id: article
            },function(data) {
                $j("span.numberOfVotes_"+data.id).html(data.votes);
            }, "json");
        }
        return false;
    });
}
});
+3
source share
3 answers

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

+12

. - :

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

HtmlUnit Javascript .

id 'a' , XPath .

+9

. .click() HtmlElement, Javascript. ( 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();
+5

Source: https://habr.com/ru/post/1768784/


All Articles