Java-使用HtmlUnit单击图像

问题描述

我正在做一个涉及从网站获取数据的个人项目,我设法使其自动登录,所有这些,但是我已经到达必须点击图片的地步

img src="data:image/png;base64,{{sc.PhotoLocation}}" style="width: 75px; margin-top:3px;cursor:pointer" class="ng-cloak" ng-click="sc.selectPerson(sc.person_Guid)" title="View Student Record" /

在经过多次Google搜索和文档整理后,我决定使用XPath进入该页面的另一个菜单

HtmlImage image = page.<HtmlImage>getFirstByXPath("//img[@src=\'data:image/png;base64,sc.PhotoLocation}}\']");

page = (HtmlPage) image.click();

问题是,我从中得到了NullPointerException,我做错了什么吗?谢谢。

其余代码

WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("https://myWebsite");

HtmlInput username = page.getElementByName("Template1$MenuList1$TextBoxUsername");
username.setValueAttribute("myUsername");
HtmlInput password = page.getElementByName("Template1$MenuList1$TextBoxPassword");
password.setValueAttribute("myPassword");

HtmlSubmitInput loginButton = page.getElementByName("Template1$MenuList1$ButtonLogin");
page = loginButton.click();
webClient.waitForBackgroundJavaScript(2000);
if (page.getElementByName("Template1$Control0$ButtonContinue") != null) {
    HtmlSubmitInput continueButton = page.getElementByName("Template1$Control0$ButtonContinue");
    page = continueButton.click();
    webClient.waitForBackgroundJavaScript(2000);
}

解决方法

您好@Orestesk欢迎来到SO,

您的xpath不正确。

您图像的

src属性是动态的。 src="data:image/png;base64,{{sc.PhotoLocation}}"

此处{{sc.PhotoLocation}}的值将为某个值。因此,src属性的值根据sc.PhotoLocation的值而不断变化。

使用其他策略来选择图像,而不要依赖src属性。

或者尝试这个技巧。

//img[contains(@src,'data:image/png;base64')]