我用htmlunit从网页上抓取图片。我是htmlunit的初学者。我编码,但不知道如何获取图像。以下是我的代码。
import java.io.*;
import java.net.URL;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class urlscrap {
public static void main(String[] args) throws Exception
{
//WebClient webClient = new WebClient(Opera);
WebClient webClient = new WebClient();
HtmlPage currentPage = (HtmlPage) webClient.getPage(new URL("http://www.google.com"));
System.out.println(currentPage.asText());
//webClient.closeAllWindows();
}
}
答案 0 :(得分:4)
这对你有用吗?
import java.net.URL;
import java.util.List;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class urlscrap {
public static void main(String[] args) throws Exception
{
//WebClient webClient = new WebClient(Opera);
WebClient webClient = new WebClient();
HtmlPage currentPage = (HtmlPage) webClient.getPage(new URL("http://www.google.com"));
//get list of all divs
final List<?> images = currentPage.getByXPath("//img");
for (Object imageObject : images) {
HtmlImage image = (HtmlImage) imageObject;
System.out.println(image.getSrcAttribute());
}
//webClient.closeAllWindows();
}
}
答案 1 :(得分:0)
看起来你正在获取页面文本,这确实是第一步。你有什么问题?您是否在查找页面中引用的所有图像时遇到问题?我建议查找如何在Java中进行DOM解析,并使用它从页面中提取所有img标记。
答案 2 :(得分:0)
如果您不介意切换语言,那么我会推荐Python的scrapy。它是迄今为止我用来刮取网页内容的最佳框架,包括图像(它甚至可以自动为你创建缩略图)。就个人而言,我不会使用java来完成这些任务。