获取网站数据

本文提供了一个使用Java抓取指定网址(如新浪网)源代码的示例程序。通过创建URL对象并利用HttpURLConnection获取网页内容,该程序能够读取并打印出网页的源代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class WebPageSource {

    public static void main(String args[]){    

        URL url;

        int responsecode;

        HttpURLConnection urlConnection;

        BufferedReader reader;

        String line;

        try{

            //生成一个URL对象,要获取源代码的网页地址为:http://www.sina.com.cn

            url=new URL("网站");
          /*  //读取目的网页URL地址,获取网页源码
            URL url = new URL(urlInfo);*/

            //打开URL

            urlConnection = (HttpURLConnection)url.openConnection();

            //获取服务器响应代码

            responsecode=urlConnection.getResponseCode();

            if(responsecode==200){

                //得到输入流,即获得了网页的内容

                reader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"GBK"));
                /*BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));*/
                while((line=reader.readLine())!=null){

                    System.out.println(line);

                }

            }

            else{

                System.out.println("获取不到网页的源码,服务器响应代码为:"+responsecode);

            }

        }

        catch(Exception e){

            System.out.println("获取不到网页的源码,出现异常:"+e);

        }

    }

}

 

转载于:https://www.cnblogs.com/kongqinyuan/p/8146451.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值