Htmlunit Javascript按钮/链接

Htmlunit Javascript Button/Link

本文关键字:链接 按钮 Javascript Htmlunit      更新时间:2023-09-26

我正在尝试查找特定源的链接/按钮。我已经设法使用"表单"属性分配了一个按钮,但我尝试按下的新按钮没有表单。下面是javascript按钮的HTML源代码:

<span class="followButtonActions" id=".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].   [1].[1]">
    <a class="Button FollowButton followButtonFollow" role="button" href="javascript:;" id=".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0">
        <span id=".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0.[0]">
        <span id=".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0.[0].[0]">Follow</span>    </span>
    </a>
</span>

到目前为止,我一直在尝试使用类来识别元素,但在页面上找不到链接/按钮。我一直在尝试使用htmlAnchor,但它不起作用,所以我切换到DOM ELEMENT。下面是我当前查找按钮/链接的代码,结果是:java.lang.NullPointerException.

final DomElement myAnchor = page3.getFirstByXPath("//span[@class='followButtonActions']");
final HtmlPage newPage = myAnchor.click();

我还尝试了以下操作,结果是:java.lang.NullPointerException.

    final HtmlSubmitInput button = page.getFirstByXPath("//class[@id='.reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0']");
    final HtmlPage newPage = button.click(); 

我已经到了什么都试的地步了!用外行的话来说,我试图将javascript链接分配给一个按钮,然后可以按下该按钮。我的方法是以某种方式将"按钮跟随按钮跟随按钮"链接到一个可以点击的按钮。任何帮助都将不胜感激。谢谢:)

如果您正在尝试获取锚标记,则应该使用XPath:

//a[@id='.reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0']

检查下面的演示代码:

import java.net.URL;
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
public class HtmlUnitAnchorExample {
    public static void main(String[] args) throws Exception {
        String html = "<html><head><title>HTMLUNIT TEST</title></head><body>" +
                "" +
                "<span class='"followButtonActions'" id='".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].   [1].[1]'"> "+
                " <a class='"Button FollowButton followButtonFollow'" role='"button'" href='"javascript:;'" id='".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0'"> "+
                "     <span id='".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0.[0]'"> "+
                "     <span id='".reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0.[0].[0]'">Follow</span>    </span> "+
                " </a> "+
                "</span>" +
                "</body></html>";
        WebClient client = new WebClient();
        HtmlPage page = HTMLParser.parseHtml(new StringWebResponse(html, new URL("http://example.com")), client.getCurrentWindow());
        System.out.println("Page title: "+page.getTitleText());
        final HtmlAnchor myAnchor = page.getFirstByXPath("//a[@id='.reactRoot[0].[0].[1].[2].{userprofile0001}.[1].[1].[1].[1].0']");
        System.out.println("Anchor found: "+myAnchor );
        final HtmlPage newPage = myAnchor .click();
        System.out.println("newPage: "+newPage);
        client.closeAllWindows();
    }
}