本文实例讲述了Java实现爬取百度图片的方法。分享给大家供大家参考,具体如下:

在以往用java来处理解析HTML文档或者片段时,我们通常会采用htmlparser(http://htmlparser.sourceforge.net/)这个开源类库。现在我们有了JSOUP,以后的处理HTML的内容只需要使用JSOUP就已经足够了,JSOUP有更快的更新,更方便的API等。

jsoup 是一款 Java 的HTML 解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据,可以看作是java版的jQuery。

jsoup的主要功能如下:

从一个URL,文件或字符串中解析HTML;

使用DOM或CSS选择器来查找、取出数据;

可操作HTML元素、属性、文本;

jsoup是基于MIT协议发布的,可放心使用于商业项目。官方网站:http://jsoup.org/

步骤大致可以分为三个模块:一是获取网页的资源,二是解析获取的资源,取出我们想要的图片URL地址,三是通过java的io存储在本地文件中。

获取网页资源的核心模块就是通过Jsoup去获取网页的内容,具体核心代码如下:

private static List findImageNoURl(String hotelId, String url, int timeOut) {

List result = new ArrayList();

Document document = null;

try {

document = Jsoup.connect(url).data("query", "Java")//请求参数

.userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")//设置urer-agent get();

.timeout(timeOut)

.get();

String xmlSource = document.toString();

result = dealResult(xmlSource, hotelId);

} catch (Exception e) {

String defaultURL = "http://qnimg.zowoyoo.com/img/15463/1509533934407.jpg";

result = dealResult(defaultURL,hotelId);

}

return result;

}

其中URL地址是百度图片搜索的地址,具体调用代码如下:

public static List findImage(String hotelName, String hotelId, int page) {

int number=5;

String url = "http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word=" + hotelName + "&cg=star&pn=" + page * 30 + "&rn="+number+"&itg=0&z=0&fr=&width=&height=&lm=-1&ic=0&s=0&st=-1&gsm=" + Integer.toHexString(page * 30);

int timeOut = 5000;

return findImageNoURl(hotelId, url, timeOut);

}

这里需要注意的是:word是我们要搜索的关键字,pn是显示的页码,rn是一页显示多少个数据。

解析网页的资源,然后封装起来。核心代码如下:

private static List dealResult(String xmlSource, String hotelId) {

List result = new ArrayList();

xmlSource = StringEscapeUtils.unescapeHtml3(xmlSource);

String reg = "objURL\":\"http://.+?\\.(gif|jpeg|png|jpg|bmp)";

Pattern pattern = Pattern.compile(reg);

Matcher m = pattern.matcher(xmlSource);

while (m.find()) {

JsoupImageVO jsoupImageVO = new JsoupImageVO();

String imageURL = m.group().substring(9);

if(imageURL==null || "".equals(imageURL)){

String defaultURL = "http://qnimg.zowoyoo.com/img/15463/1509533934407.jpg";

jsoupImageVO.setUrl(defaultURL);

}else{

jsoupImageVO.setUrl(imageURL);

}

jsoupImageVO.setName(hotelId);

result.add(jsoupImageVO);

}

return result;

}

这里最主要的地方就是reg这个正则表达式,通过正则表达式,去网页中解析符合规定的图片URL地址,然后封装在对象中。

最后一部分就是通过java的io流去图片地址获取图片,并保存在本地。核心代码如下:

//根据图片网络地址下载图片

public static void download(String url,String name,String path){

File file= null;

File dirFile=null;

FileOutputStream fos=null;

HttpURLConnection httpCon = null;

URLConnection con = null;

URL urlObj=null;

InputStream in =null;

byte[] size = new byte[1024];

int num=0;

try {

dirFile = new File(path);

if(dirFile.exists()){

dirFile.delete();

}

dirFile.mkdir();

file = new File(path+"//"+name+".jpg");

fos = new FileOutputStream(file);

if(url.startsWith("http")){

urlObj = new URL(url);

con = urlObj.openConnection();

httpCon =(HttpURLConnection) con;

in = httpCon.getInputStream();

while((num=in.read(size)) != -1){

for(int i=0;i

fos.write(size[i]);

}

}

}catch (FileNotFoundException notFoundE) {

LogUtils.writeLog("找不到该网络图片....");

}catch(NullPointerException nullPointerE){

LogUtils.writeLog("找不到该网络图片....");

}catch(IOException ioE){

LogUtils.writeLog("产生IO异常.....");

}catch (Exception e) {

e.printStackTrace();

}finally{

try {

fos.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

这里面的操作都是java中io篇一些基础的操作,有不懂的可以去看看java中io模块的内容。

因为我这边是maven项目,所以在开发前需要引入Jsoup依赖才可以。

源码可点击此处本站下载。

希望本文所述对大家java程序设计有所帮助。

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐