HtmlAnchor click() function in Htmlunit is not working

送分小仙女□ 提交于 2019-12-11 03:59:37

问题


I am trying to use HtmlUnit for browsing automatically a site. I need to press some buttons in the process. First I build an HtmlAnchor object of a button with this xml:

<a href="dog.php">
  <img src="http://images.hand.co.uk/Pic/site_images/hand/Myper/MyOrder/images/DogRed.gif" width="75" height="31" border="0" alt="1 adds"/>
</a>

which works fine when I click it using the click() method. I am then moved to another page in which I have link on which I need to click for the desired contents to appear. After the click I am not moved to another page and it is merely a Java script function firing.

this is the anchor for the second link:

<a style="color: black; font-weight: bold;" href="javascript:show_me('DogDetails.php?DogID=2445485', 2445485, 800);">
  details
</a>

For both of those elements I am using the HtmlAnchor object with it's click() method. But that method is doing nothing at all for the second element.

I have also tried using the JavaScript Engine built in HtmlUnit, but had no success. how can I click this persistent link with the HtmlUnit platform?


回答1:


The most likely problem is that HtmlUnit isn't waiting for the JavaScript to finish running. The HtmlUnit FAQ suggests 3 workarounds: http://htmlunit.sourceforge.net/faq.html#AJAXDoesNotWork.

Of these, the neatest solution to try is to get your WebClient to wait for AJAX requests to finish:

webClient.setAjaxController(new NicelyResynchronizingAjaxController());

I have found that some sites do a clever trick of running AJAX on a background thread - this means the NicelyResynchronizingAjaxController won't wait for it to finish, as it only watches the main UI thread. There's a good answer here that explains how to wait for all threads rather than just the main one.




回答2:


I've had a somewhat similar problem, tried several ways to wait for javascript to run in the background, but had no success.

I had half a mind to switch to Selenium, but it "solved itself" after disabling CSS on the WebClient:

WebClient.getOptions().setCssEnabled(false);

Whenever we reenable the CSS, the .click() just stops working.

My anchor was:

<div class="my-anchor's-parent-class"/>
  <a href="javascript:void(0) class="text" id="buttonSearch" style="display: block;">Search</a>
</div>

It had some JQuery attaching the .click() handler to it, who acted based on the 'class' property of my anchor's parent:

    $('.my-anchor's-parent-class').each(function () {
        $(this).children('a').click(function () {
          // if parent has another given class appended, call .myFunction(this)
          // else, call other function
        });
    });


来源:https://stackoverflow.com/questions/12217889/htmlanchor-click-function-in-htmlunit-is-not-working

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