java爬取百度首页源代码

爬虫感觉挺有意思的,写一个最简单的抓取百度首页html代码的程序。虽然简单了一点,后期会加深的。

 1 package test;
 2 
 3     import java.io.BufferedReader;
 4     import java.io.InputStreamReader;
 5     import java.net.URL;
 6     import java.net.URLConnection;
 7 
 8     public class Main
 9     {
10         public static void main(String[] args)
11         {
12             // 定义即将访问的链接
13             String url = "https://www.baidu.com/";
14             // 定义一个字符串用来存储网页内容
15             String result = "";
16             // 定义一个缓冲字符输入流
17             BufferedReader in = null;
18             try
19             {
20                 // 将string转成url对象
21                 URL realUrl = new URL(url);
22                 // 初始化一个链接到那个url的连接
23                 URLConnection connection = realUrl.openConnection();
24                 // 开始实际的连接
25                 connection.connect();
26                 // 初始化 BufferedReader输入流来读取URL的响应
27                 in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
28                 // 用来临时存储抓取到的每一行的数据
29                 String line;
30                 while ((line = in.readLine()) != null)
31                 {
32                     // 遍历抓取到的每一行并将其存储到result里面
33                     result += line + "\n";
34                 }
35             } catch (Exception e)
36             {
37                 System.out.println("发送GET请求出现异常!" + e);
38                 e.printStackTrace();
39             } // 使用finally来关闭输入流
40             finally
41             {
42                 try
43                 {
44                     if (in != null)
45                     {
46                         in.close();
47                     }
48                 } catch (Exception e2)
49                 {
50                     e2.printStackTrace();
51                 }
52             }
53             System.out.println(result);
54         }
55     }
56     

 

转载于:https://www.cnblogs.com/cppeterpan/p/7050970.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值