java简易爬虫


源码来源:https://github.com/KKys


详细解释见代码注释


 功能:提取网页中的图片地址,觉得很有趣,于是抄了一遍并且自己重写了一遍注释





/*  Spider
*
*   @author https://github.com/KKys
*
*   注释&修改 by lewis.
*
*
* */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args)
    {
        String url = "https://www.zhihu.com/question/49168520";
        String result = sendGet(url);//获得网页源码
     System.out.println(result);

       RegexString(result,"src=\"(.+?)g\"");//使用正则匹配图片网址,打印符合图片地址。

    }

    // 静态static方法中不能调用非静态non-static方法
    static String sendGet(String url)
    {
        StringBuffer result= new StringBuffer("");//使用StringBuffer效率更高
        BufferedReader in = null;
        try
        {
            URL realURL = new URL(url);
            URLConnection connection = realURL.openConnection();//返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
            connection.connect();
            /*
            *打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
            *如果在已打开连接(此时 connected 字段的值为 true)的情况下调用 connect 方法,则忽略该调用。
            * */
            in = new BufferedReader(new InputStreamReader(
            connection.getInputStream()/*返回从此打开的连接读取的输入流。
            在读取返回的输入流时,如果在数据可供读取之前达到读入超时时间,则会抛出 SocketTimeoutException。 */));
            String line;
            while((line = in.readLine())!=null)/*读取一个文本行。通过下列字符之一即可认为某行已终止:
                                                换行 ('\n')、回车 ('\r') 或回车后直接跟着换行。*/
            {
                result.append(line+"\n");//将指定的字符串追加到此字符序列
            }
        }
        catch(Exception e)
        {
            System.out.println(e.toString());
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if(in==null)
                {
                    in.close();//关闭连接
                }
            }
            catch(Exception e)
            {
                 e.printStackTrace();
            }
        }
        return result.toString();
    }
    static void RegexString(String targetStr,String patternStr)
    {
        Pattern pt = Pattern.compile(patternStr);//编译正则
        Matcher ma= pt.matcher(targetStr);//匹配模式串
        while(ma.find())//打印所有匹配字符串
        {
            System.out.println(ma.group());
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值