zoukankan      html  css  js  c++  java
  • 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 + "
    ";
    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     
  • 相关阅读:
    回到顶部
    侧边横幅特效
    中部导航吸顶
    scroll
    层次化索引MultiIndex
    pandas处理缺失值df.dropna( )的thresh参数
    pd.Index(ser2).get_indexer(ser1),返回ser1中各元素在ser2中的索引位置
    FutureWarning
    数据框索引行
    对字典dict使用最大值函数max
  • 原文地址:https://www.cnblogs.com/cppeterpan/p/7050970.html
Copyright © 2011-2022 走看看