如何在 HtmlUnit 中通过 Xpath 获取图像?

How to get an Image by Xpath in HtmlUnit?

我试图从 HtmlUnit 中的 XPath 获取图像,但我尝试的方法对我不起作用。

这是我尝试获取的元素:

<div id="image" style="width: 300px; height: 57px;"><img id="image_id" alt="Bild" height="57" width="300" src="snip"></div>

这是我的代码:

final List<?> divs = form.getByXPath("//div[@id='recaptcha_widget_div']//div[@id='recaptcha_image']");
HtmlImage img = (HtmlImage) imgs.get(0);

我知道我无法将 Division 转换为 HtmlImage,但我不知道如何从 Division 获取图像。

该元素有一个 img 标签。您应该将其 XPath 与浏览器一起使用并在 HtmlUnit getFirstByXPath 中使用并将其放入 HtmlImage:

HtmlImage img = myPage.getFirstByXPath("//img[@id='image_id'])");

但是如果你有一个元素 id,我建议你使用 .getElementById(String id) 方法。