如何使用java代码,爬取页面特定内容?
1、确认目标我们要爬取的是“百度”首页
中的 gif 动态图
将它下载下来
2、加入jsoup依赖
我这里使用的是maven,进行的依赖管理
如果不知道maven是什么可以去百度了解一下
3、依赖有了我们就开始编码吧
第一步:先把“百度”首页所有的html元素内容全部爬下来
4、第二步:找到我们需要的图片元素 对象
使用 css 选择器
jsoup已经为我们封装好了,一起来看吧
5、第三步:获取图片的网络路径
6、第四步:通过网络图片地址,将图片下载到本地
7、代码都在这里了 :
public static void main(String [] args) throws IOException {
Document doc = Jsoup.connect("http://www.baidu.com/").get();
Elements select = doc.select(".index-logo-src");
int i = 1;
java.net.URL url = null;
for (Element element : select) {
String src = element.attr("src");
src = src.substring(2);
src = "http://" + src;
url = new java.net.URL(src);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File("e:/img/" + (i) + ".gif"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
byte[] bytes = output.toByteArray();
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
i++;
}
}
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:82
阅读量:173
阅读量:31
阅读量:30
阅读量:159