java爬取百度首页logo

时间:2014-09-24 02:25:37   收藏:0   阅读:690

它包括两个类:Pattern和Matcher 。

Pattern: 创建匹配模式字符串。

Matcher:将匹配模式字符串与输入字符串。


package com.test;
 
import java.io.*;
import java.net.*;
import java.util.regex.*;
 
public class baidulogo {
    static String  getUrlContentString(String urlString) throws Exception {
        String result = "";
        URL url = new URL(urlString);
        URLConnection urlConnection = url.openConnection();
        urlConnection.connect();
        InputStreamReader inputStreamReader = new InputStreamReader(
                urlConnection.getInputStream(), "utf-8");
        BufferedReader in = new BufferedReader(inputStreamReader);
        String line;
        while ((line = in.readLine()) != null)  {
            result += line;
        }
        return result;
    }
 
    static String  getLogoUrl(String contentString, String patternString) {
        String LogoUrl = null;
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(contentString);
        if (matcher.find()) {
            LogoUrl = matcher.group(1);
        }
        return LogoUrl;
 
    }
 
    public staticvoid main(String[] args) throws Exception {
        // 定义即将访问的链接
        String urlString = "http://www.baidu.com";
        String result = getUrlContentString(urlString);
        String patternString = "src=\"(.+?)\"";
        String contentString = result;
        String logoUrl = getLogoUrl(contentString, patternString);
        System.out.println(logoUrl);
    }
}



原文:http://6023891.blog.51cto.com/6013891/1557516

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!