자바 파충류 인 스 턴 스 - 웹 페이지 를 오 르 는 url

10935 단어 자바
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WebSpider {
    //    
    public static String getURLContext(String urlStr,String charsetName){
        StringBuffer sb=new StringBuffer();
        try{
            URL url =new URL(urlStr);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName( charsetName)));
            String temp="";
            while((temp=reader.readLine())!=null){
                // System.out.println(temp);
                sb.append(temp);
            }
        }catch(MalformedURLException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    public static List<String> getSubStrs(String destStr,String regexStr){
        Pattern p=Pattern.compile(regexStr);//      
        Matcher m=p.matcher(destStr);
        List<String>result = new ArrayList<String>();
        while (m.find()) {
            result.add(m.group());
        }
        return result;
    }
    public static void main(String args[]){
        String urlStr="https://daohang.qq.com/?fr=hmpage";

        String destStr=getURLContext(urlStr,"utf-8");
        String regexStr="href=\"([\\w\\s./:]+?)\"";     //          
        List<String>result=getSubStrs(destStr, regexStr);
        for(String temp:result ){
             System.out.println(temp);
        }
    }
}

좋은 웹페이지 즐겨찾기