本文实例讲述了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的主要功能如下:
jsoup是基于MIT协议发布的,可放心使用于商业项目。官方网站:http://jsoup.org/
步骤大致可以分为三个模块:一是获取网页的资源,二是解析获取的资源,取出我们想要的图片URL地址,三是通过java的io存储在本地文件中。
获取网页资源的核心模块就是通过Jsoup去获取网页的内容,具体核心代码如下:
private static List<JsoupImageVO> findImageNoURl(String hotelId, String url, int timeOut) {
List<JsoupImageVO> result = new ArrayList<JsoupImageVO>();
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 = "https://cache.yisu.com/upload/information/20200623/121/99971.jpg";
result = dealResult(defaultURL,hotelId);
}
return result;
}
其中URL地址是百度图片搜索的地址,具体调用代码如下:
public static List<JsoupImageVO> 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<JsoupImageVO> dealResult(String xmlSource, String hotelId) {
List<JsoupImageVO> result = new ArrayList<JsoupImageVO>();
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 = "https://cache.yisu.com/upload/information/20200623/121/99971.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<num;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相关内容感兴趣的读者可查看本站专题:《Java网络编程技巧总结》、《Java Socket编程技巧总结》、《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。