java如何从网页的源码中得到图片的链接
URLurl=newURL("http://www.baidu.com");HttpURLConnectionhttp=(HttpURLConnection)url.op...
URL url = new URL("http://www.baidu.com");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("GET");
http.setConnectTimeout(5*1000);
InputStream fis = http.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while((len = fis.read(buffer))!= -1){
out.write(buffer, 0, len);
}
System.out.println(out.toString); //这样可以得到源码 但是后面就不知道怎么写了,用DOM要怎么写 展开
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("GET");
http.setConnectTimeout(5*1000);
InputStream fis = http.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while((len = fis.read(buffer))!= -1){
out.write(buffer, 0, len);
}
System.out.println(out.toString); //这样可以得到源码 但是后面就不知道怎么写了,用DOM要怎么写 展开
2个回答
展开全部
import java.util.regex.*;
.............
URL url = new URL("http://www.baidu.com");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("GET");
http.setConnectTimeout(5*1000);
InputStream fis = http.getInputStream();
java.io.InputStreamReader is=new java.io.InputStreamReader(fis);
char[] buffer = new char[1024];
int len = 0;
java.io.StringWriter str=new java.io.StringWriter();
while((len = is.read(buffer))!= -1){
str.write(buffer, 0, len);
}
System.out.println(str.getBuffer());
Pattern p=Pattern.compile("img\\s+src\\s*=\\s*(\"[^\"]*\"|'[^']*')");
Matcher m=p.matcher(str.getBuffer().toString());
while(m.find()){
int slen;
String imgsrc;
imgsrc=m.group();
slen=imgsrc.length();
char c=imgsrc.charAt(slen-1);
System.out.println(imgsrc.substring(imgsrc.indexOf(c)+1, slen-1));
}
可能写的不精简,不过能实现功能
.............
URL url = new URL("http://www.baidu.com");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("GET");
http.setConnectTimeout(5*1000);
InputStream fis = http.getInputStream();
java.io.InputStreamReader is=new java.io.InputStreamReader(fis);
char[] buffer = new char[1024];
int len = 0;
java.io.StringWriter str=new java.io.StringWriter();
while((len = is.read(buffer))!= -1){
str.write(buffer, 0, len);
}
System.out.println(str.getBuffer());
Pattern p=Pattern.compile("img\\s+src\\s*=\\s*(\"[^\"]*\"|'[^']*')");
Matcher m=p.matcher(str.getBuffer().toString());
while(m.find()){
int slen;
String imgsrc;
imgsrc=m.group();
slen=imgsrc.length();
char c=imgsrc.charAt(slen-1);
System.out.println(imgsrc.substring(imgsrc.indexOf(c)+1, slen-1));
}
可能写的不精简,不过能实现功能
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |