Java - 使用 HtmlUnit 单击图像

Java - Clicking on an image using 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.

的值不断变化

使用其他策略 select 您的图像,而不是依赖 src 属性。

或者试试这个技巧。

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