Java网络爬虫(Java代码读取某一个网页中的所有图片)
1、具体步骤
- 指定目标文件
- 获取URL对象
- 通过URL开启java程序与资源的连接
- 将资源读取到io流中
- 文件拷贝操作
2、单个网络资源的下载
public static void main(String[] args) {
//目标文件的位置
String src= "http://www.slxy.cn/__local/4/16/35/539C388F0600C11218D95E1B821_869968B2_22712.jpg";
try {
//获取URL对象
URL url = new URL(src);
//通过url开启java程序与资源的连接connection
URLConnection oc = url.openConnection();
//将资源读取到io流中
InputStream is = oc.getInputStream();
//文件拷贝操作
IOUtils.copy(is, new FileOutputStream(new File("E:\\new.jpg")));
System.out.println("文件拷贝完成");
//关闭资源
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3、目标路径中的所有需要的资源文件的下载,多文件下载
注意事项:
- 不同的网页结构,要使用不同的正则表达式来处理
//获取该网页中所有的图片信息
public static void getAllimg(){
int index = 0;
//指定目标文件
String address = "http://www.slxy.cn/info/1187/11677.htm";
try {
//创建URL对象
URL url = new URL(address);
//建立连接
URLConnection openConnection = url.openConnection();
//将源文件读取到io流中
InputStream inputStream = openConnection.getInputStream();
//为了增加读写速度,把他加到转换流中,变为字符缓冲流
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(isr);
//读取每一行数据
String buff = null;
while((buff = br.readLine()) != null) {
/**
* 使用正则表达式来获取页面中的所有img标签
*/
/*
* 正则表达式使用步骤
* 使用pattern定义正匹配规则
* 进行匹配,将结果保存到matcher中
* 从matcher获取匹配结果
*/
Pattern patt = Pattern.compile("<img.*src\\s*=\\s*(.*?)>");
//对每行数据进行匹配
Matcher matcher = patt.matcher(buff);
while(matcher.find()) {
//得到每一个img标签
String group = matcher.group();
//获取每一个img标签中的src的内容
Pattern spatt = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>\\s+)");
Matcher smatcher = spatt.matcher(group);
int count = 0;
while(smatcher.find()) {
count++;
index++;
if(count/2==0) {
smatcher.find();
}
}
String group2 = smatcher.group();
/*
* 再获得src的具体值
*/
Pattern compile = Pattern.compile("/.*jpg");
Matcher matcher2 = compile.matcher(group2);
matcher2.find();
String group3 = matcher2.group();
//下载路径
String path = "http://www.slxy.cn"+group3;
//下载之后的文件的名字
String name = "slxy"+index+".jpg";
/*
* 开始最后的下载
*/
URL imgurl = new URL(path);
URLConnection openConnection2 = imgurl.openConnection();
InputStream inputStream2 = openConnection2.getInputStream();
IOUtils.copy(inputStream2, new FileOutputStream(new File("E:\\",name)));
System.out.println("第"+index+"个文件下载成功");
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}