网络编程(三)URL爬虫原理

URL和URI的概念

URI(Uniform resource identifier)统一资源标识符,用来唯一的标识一个资源

URL(Uniform resource Locator)统一资源定位符,他是一种具体的URI

统一资源定位符,由四部分组成:协议、存放资源的主机域名、端口号和资源文件名

URL是指向互联网  资源  的指针

资源可以是简单的目录或文件,也可以是对更为复杂对象的引用,例如对数据库或搜索引擎的查询

 

URL的构建

 常用的为:

URL(String spec)         //绝对路径构建

 

URL(URL context, String spec)  //相对路径构建

一个例子:

public static void main(String[] args) throws MalformedURLException {

/**
* URL组成 协议、存放资源的主机域名、端口号和资源文件名
* http 协议   www.baidu.com:80 主机域名  80端口  index.jsp资源
*/
    //绝对路径创建
    URL url1 = new URL("http://www.baidu.com:80/index.jsp"); 
    System.out.println(url1.toString());

    //相对路径创建
    URL url = new URL("http://www.baidu.com:80");
    URL url2 = new URL(url,"/login.html"); 
    System.out.println(url2.toString());

}

输出:

http://www.baidu.com:80/index.jsp

http://www.baidu.com:80/login.html

 

URL的常用方法

另一个例子:

public static void main(String[] args) throws MalformedURLException {

    //绝对路径创建
    URL url = new URL("http://www.baidu.com:80/index.jsp#aa?dmcId=1"); 

    System.out.println(url.toString());
    System.out.println("协议:" + url.getProtocol());
    System.out.println("主机名:" + url.getHost());
    System.out.println("端口:" + url.getPort());
    System.out.println("资源:" + url.getFile());
    System.out.println("相对路径资源:" + url.getPath());
    System.out.println("锚点:" + url.getRef()); //锚点 #aa
    System.out.println("有锚点时参数:" + url.getQuery()); //存在锚点返回null 不存在锚点返回参数
    url = new URL("http://www.baidu.com:80/index.jsp?dmcId=1");
    System.out.println("无锚点时参数:" + url.getQuery());
}

输出:

http://www.baidu.com:80/index.jsp#aa?dmcId=1
协议:http
主机名:www.baidu.com
端口:80
资源:/index.jsp
相对路径资源:/index.jsp
锚点:aa?dmcId=1
有锚点时参数:null

无锚点时参数:dmcId=1

 

利用URL进行文件读取

​public static void readrUrl() throws Exception{

URL url = new URL("http://www.baidu.com");
InputStream is = url.openStream();

//用UTF-8进行解码
BufferedReader reader = new BufferedReader(
new InputStreamReader(is,"utf-8"));

String msg = null;
while(null != (msg = reader.readLine())){
System.out.println(msg);
}
reader.close();
}

​

​

输出:百度首页的源码

将结果存储到本地

public static void readrUrl() throws Exception{

URL url = new URL("http://www.baidu.com");
InputStream is = url.openStream();
File file = new File("d:\\baidu.html");
FileOutputStream os = new FileOutputStream(file);

//用UTF-8进行解码
BufferedReader reader = new BufferedReader(
new InputStreamReader(is,"utf-8"));
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(os,"utf-8"));

String msg = null;
while(null != (msg = reader.readLine())){
bw.append(msg);
bw.newLine();
}
bw.flush();
bw.close();
reader.close();
}

自学笔记,多有不足!!!!

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值