欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用Java打造全方位网络爬虫(音频、视频和商业数据篇)

最编程 2024-08-03 18:14:51
...

  Java实现网络爬虫

      • 1.URL类和URLConnection扩展
        • 1.1URL学习
        • 1.2URL的基本使用 案例
        • 1.3URL的应用举例
        • 1.4. URLConnection使用方法(通过URL进而获取到 选讲)
          • 1.4.1使用URLConnection对象一般分为以下7步
        • 1.5.URLConnection 的简介和基本用法
        • 1.6.利用url爬取网页的图片
      • 2.Commons-io.jar大大简化处理io流和操作文件
        • 2.1Commons讲解
        • 2.2.Commons主要的类和方法
        • 2.3.FileUtils工具类的使用案例 ( 简单好用 )
      • 3.Jsoup
        • 3.1.Jsoup解释
        • 3.2.爬取文本案例
        • 3.3.批量爬取网络图片
        • 3.4.利用Jsoup实现爬取音视频资源
      • 4.利用jsoup爬取招聘网站(中华英才网)
        • 画图分析(简单易理解)
        • 4.1首先写一个job类
        • 4.2写一个爬虫处理类
        • 4.3写一个Excell存储处理类
        • 4.4.最后写一下爬虫的测试类

1.URL类和URLConnection扩展

1.1URL学习
  • (Uniform Resource Locator)中文名为统一资源定位符,也被俗称为网页地址。表示为互联网上的资源,如网页或者FTP地址但是在Java中表示为处理网页请求的一个类,Java的URL类可以让访问网络资源就像是访问你本地的文件夹一样方便快捷。我们通过使用java.net.URL;的URL类 就可以经由URL完成读取和修改数据的操作。通过一个URL连接,我们就可以确定资源的位置,

  • 简而言之:通过URL类可以使Java程序很方便的操作网络资源

  • 小结:URL类就是一个网络资源操作的类

1.2URL的基本使用 案例
package com.Li.url01;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * @Description: url的基本使用
 * @auther:Li Ya Hui
 * @Time:2021年4月24日上午10:46:38
 */
public class Test {
	public static void main(String[] args) throws MalformedURLException {
		//1.指定网络资源地址  路径字符串
		String urlpath = "https://so.youku.com/search_video/q_%E9%92%A2%E9%93%81%E4%BE%A0?spm=a2hww.11359951.#qheader_search~10";
		//2.初始化URL类
		URL realurl = new URL(urlpath);		
		//请求网络主机
		System.out.println("主机是:"+realurl.getHost());
		//协议
		System.out.println("协议是:"+realurl.getProtocol());
		//默认端口
		System.out.println("默认的端口是:"+realurl.getDefaultPort());
		//请求参数
		System.out.println("请求参数是:"+realurl.getQuery());
	}
}
1.3URL的应用举例
  • 通过URL获取HTML的内容实现另存为

  • 百度大部分标签通过动态加载(反爬虫的一种)实现,所以目前方法有所限制

package com.Li.url02;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Description:  URL的应用举例 :通过URL获取HTML的内容
 * @auther:Li Ya Hui
 * @Time:2021年4月24日上午11:05:22
 */
public class Test {

	public static void main(String[] args) throws IOException {
		//实例化一个URL对象
		URL url = new URL("http://www.baidu.com"); 
		//根据url对象获取一个输入流
		InputStream is = url.openStream();
		//设定输入流的编码集为utf-8
		InputStreamReader isr = new InputStreamReader(is, "utf-8");
		//加入到缓存读取对象中
		BufferedReader br = new BufferedReader(isr);
		//设置要保存的路径,
		File filepath = new File("E://zp");//要创建目录 的路径
		File file = new File("E://zp//baidu.html");
		//创建目录
		filepath.mkdirs();
		//将file加入到print writer对象中
		PrintWriter pwriter = new PrintWriter(file);
		//创建一个行数
		String hang= "";
		while ((hang=br.readLine())!=null) {//循环逐行读取
			pwriter.print(hang);
			pwriter.write(hang);
			pwriter.flush();
		}
		//关闭打印流
		pwriter.close();
		//关闭缓冲流
		br.close();
		//关闭输入流
		isr.close();
		//关闭输入获取流
		is.close();
	}
}
1.4. URLConnection使用方法(通过URL进而获取到 选讲)
  • URLConnection是URL类的升级,其目的是更加方便的进行网络资源的请求和操作的
  • 利用可以实现简单的爬虫
1.4.1使用URLConnection对象一般分为以下7步

1:创建一个URL对象;

2:通过URL对象的openConnection方法创建URLConnection对象;

3:通过URLConnection对象提供的方法可以设置参数和一般请求属性。常用的请求属性设置方式有以下几种:

  • ~public void setRequestProperty(String key,String value)设置指定的请求关键字对应的值

  • ~public void setDoInput(boolean doinput)设置是否使用URL连接进行输入,默认值为true

  • ~public void setDoOutput(boolean dooutput)设置是否使用URL连接进行输出,默认值为false,如果设置为true,就可以获取一个字节输出流,用于将数据发送到服务器

  • ~public void setUseCaches(boolean usecaches)设置此连接是否使用任何可用的缓存,默认值为true

4:调用URLConnection对象的connect方法连接到该远程资源

5:连接到服务器后,就可以查询头部信息了,查询头部信息常用方法有以下几种:

  • ~public String getHeaderField(String name)返回指定头字段的值

  • ~public Map<String,List>getHeaderFields()返回头字段的不可修改的Map

  • ~public String getContentType()返回content-type头字段的值

  • ~public String getContentEncoding()返回content-encoding的值

6:获取输入流访问资源数据。使用getInputStream 方法,获取一个字节输入流,以便读取资源信息

7:获取输出流并写数据

1.5.URLConnection 的简介和基本用法
package com.Li.url01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * @Description:  URLConnection 的简介和基本用法
 * @auther:Li Ya Hui
 * @Time:2021年4月24日下午10:08:22
 */
public class Test03 {
	public static void main(String[] args) throws IOException {
		//1.创建URL对象
		URL url = new URL("https://search.51job.com/list/010000,000000,0000,00,9,99,java,2,1.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare=");
	   //2.通过URL对象中的openConnection()方法创建URLConnection对象
		URLConnection connection = url.openConnection();
		//3.调用URLConnection对象提供的connect方法连接远程服务
		connection.connect();
		//4.连接服务器后,就可以查询头部信息了
		Map<String,List<String>> headerMap = connection.getHeaderFields();
		Set<String> keySet = headerMap.keySet();
		Iterator<String> it = keySet.iterator();
		//遍历出爬到的,获取标题字段
		while (it.hasNext()) 
		{
		String key = it.next();	
		List<String> list = headerMap.get(key);
		StringBuffer sb=new StringBuffer();
		for (int i = 0; i <list.size(); i++)
		  {
			if(i>0)
			{
				sb.append(",");
			}
			  String str = list.get(i);
			  sb.append(str);
		 }
//		System.out.println(key+":"+sb);
		}
		//整体html
		//6.获取输入流,从中读取资源数据
		 InputStream inputStream = connection.getInputStream();
		 InputStreamReader reader=new InputStreamReader(inputStream);
		 BufferedReader bufferedReader=new BufferedReader(reader);
		 String line="";
		 while ((line=bufferedReader.readLine())!=null) 
		 {
			System.out.println(line);
		 }
		//7.关闭流对象
		 bufferedReader.close();
		 reader.close();
		 inputStream.close();
	}
}
1.6.利用url爬取网页的图片
package com.Li.url01;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
/**
 * @desc   利用url爬取网页的图片   UrlConnection实现图片的下载
 * @author wyh
 * @time   2018-08-22
 *
 */
public class Test04 {
public static void main(String[] args) throws IOException {
	
	//1.创建URL对象
	URL url = new URL("https://imgsa.baidu.com/forum/w%3D580/sign=a6b7ab9a10dfa9ecfd2e561f52d1f754/48c7a7efce1b9d16a99e53e7f2deb48f8d5464d8.jpg");
   //2.通过URL对象中的openConnection()方法创建URLConnection对象
	URLConnection connection = url.openConnection();
	//3.调用URLConnection对象提供的connect方法连接远程服务
	   // 设定请求的方法,默认是GET
	 connection.setRequestProperty("method", "GET");
	   // 设置字符编码
	connection.setRequestProperty("Charset", "UTF-8");

	 connection.connect();
	 int fileLength = connection.getContentLength();//获取文件的大小
	 //4.在客户端(Test04.java)与服务端(网页)建立一个输入流
	 InputStream inputStream = connection.getInputStream();
	 //5.将输入流转变成缓冲流
	 BufferedInputStream bin = new BufferedInputStream(inputStream);
	 
	 //6.设定图片保存的路径
	   String path = "E:\\zp\\uc\\1.jpg";
	   File file = new File(path);//根据路径开辟一个内存文件
	   //如果路径不存在就创建一个路径
	   if (!file.getParentFile().exists()) {
		    file.getParentFile().mkdirs();
		   }
       //创建一个输出流
	   OutputStream out = new FileOutputStream(file);
	   int size = 0;
	   int len = 0;
	   byte[] buf = new byte[1024];//构建一个缓冲区块
	   while ((size = bin.read(buf)) != -1) //逐行去读
	   {
	    len += size;
	    out.write(buf, 0, size);//写入
	    // 打印下载百分比
	     System.out.println("下载了-------> " + len * 100 / fileLength +"%\n");
	   }
	   //关闭流对象
	   bin.close();
	   out.close();
	   inputStream.close();
	}	
}

2.Commons-io.jar大大简化处理io流和操作文件

2.1Commons讲解
  • commons-io:是一款处理io流的工具包,封装了很多处理io流和文件的方法,可以大大简化我们处理io流和操作文件的代码。

  • 从commons-io的官方使用文档可以看出,它主要分为

    • 工具类
    • 尾端类
    • 迭代器
    • 文件过滤器
    • 文件比较器
    • 扩展流
  • 简而言之:是Apache基金会出产的一个能更加方便进行i/o操作的jar

  • 官网地址:http://commons.apache.org/proper/commons-io/

  • 下载 :http://commons.apache.org/proper/commons-io/download_io.cgi

2.2.Commons主要的类和方法

工具类包括:FileUtils、IOUtils、FilenameUtils和FileSystemUtils,前三者的方法并没有多大的区别,只是操作的对象不同,

  • FileUtils主要操作File类;FileUtils:处理文件的打开,移动,读取和判断文件是否存在
  • IOUtils主要操作IO流;
  • FilenameUtils则是操作文件名;
  • FileSystemUtils包含了一些JDK没有提供的用于访问文件系统的实用方法。
2.3.FileUtils工具类的使用案例 ( 简单好用 )
package com.Li.Commmons;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import org.apache.commons.io.FileUtils;
/**
 * @Description: 利用Commons-io.jar创建文件的工具类
 * @auther:Li Ya Hui
 * @Time:2021年4月25日上午11:05:45
 */
public class FileTools {
	/**
	 * @desc   1.读取文件中的每一行
	 * @param  pathname
	 * @throws IOException
	 */
	public  void  getLinesByRead(String pathname) throws IOException{
		//下面的代码用于读取磁盘上的某个文件
		File file=new File(pathname);
		List<String> list = FileUtils.readLines(file, "GBK");
		for (String every : list)
		{
		  System.out.println(every);	
		}
	}
	/**
	 * @desc  2.将字符串写入到文件中
	 * @param pathname
	 * @param str
	 * @throws IOException
	 */
	public void strWriteToFile(String pathname,String str) throws IOException
	{
		File file=new File(pathname);
		FileUtils.writeStringToFile(file, str, "GBK", true);
		System.out.println("字符串写入成功了");
	}
	/**
	 * @desc  3.逐行写入文件中,但是效果会是文件的复制
	 * @param srcPath
	 * @param purposePath
	 * @throws IOException
	 */
	public void strWriteToFile2(String srcPath,String purposePath) throws IOException
	{
		File file =new File(srcPath);
		List<String> line = FileUtils.readLines(file, "GBK");//逐行的读取
		File file2=new File(purposePath);
		FileUtils.writeLines(file2, line);
		System.out.println("逐行写入文件成功了");
	}
	/**
	 * @desc  4.文件复制
	 * @param srcPath
	 * @param purposePath
	 * @throws IOException
	 */
	public void fileCopy(String srcPath,String purposePath) throws IOException
	{
		File srcFile=new File(srcPath);
		File purposeFile=new File(purposePath);
		FileUtils.copyFile(srcFile, purposeFile);
		System.out.println("文件复制成功了");
	}
	/**
	 * @desc  5.根据URL进行赋值,产生的结果就是相当于是另存为
	 * @param url
	 * @param pathname
	 * @throws Exception
	 */
	public void urlSaveAsFile(String url,String pathname) throws Exception
	{
		URL urlHtml=new URL(url);
		File file=new File(pathname);
		FileUtils.copyURLToFile(urlHtml, file);
		System.out.println("另存为成功了");
	}
	/**
	 * @desc  6.删除路径下的文件和文件夹
	 * @param pathname
	 * @throws Exception
	 */
	public void delete(String pathname) throws Exception
	{
	  File file=new File(pathname);
	  FileUtils.deleteDirectory(file);
	}
}

//测试类
package com.Li.Commmons;
/**
 * @Description: 测试类:测试Common-io包
 * @auther:Li Ya Hui
 * @Time:2021年4月25日上午11:05:16
 */
public class Test01 {
	public static void main(String[] args) throws Exception  {
	    //实例化工具类
		FileTools  fts=new FileTools();
		//读取文件中的每一行
		fts.getLinesByRead("E:/123.txt");
		//将字符串写入到文件中
		fts.strWriteToFile("E:/123.txt", "沙漠之舟aaa");
		//逐行写入文件,文件复制
		fts.strWriteToFile2("E:/123.txt", "F:/123.txt");
		//文件的复制
	    fts.fileCopy("E:/123.txt", "E:/cp/666.txt");
		//网络音频的下载
		fts.urlSaveAsFile("https://d-ring.i4.cn/audio/2019/09/02/15/1567407708580_446168.mp3", "E:/cp/mp3/123.mp3");
		//文件夹的删除
		fts.delete("E:/cp");
	}
}

3.Jsoup

3.1.Jsoup解释

1.Jsoup:是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据

  • 简而言之:Jsoup就是一个第3方的jar包,可以帮助我们很方便的实现爬虫

2.主要功能:

  • 从一个URL,文件或字符串中解析HTML;
  • 使用DOM或CSS选择器来查找、取出数据;
  • 可操作HTML元素、属性、文本;

3.Jsoup的官方网址:http://www.open-open.com/jsoup/parsing-a-document.htm

3.2.爬取文本案例
package com.Li.Jsoup.Test;
import java.io.IOException;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
 * @Description:  爬取文本的测试类 //学校官网
 * @auther:Li Ya Hui
 * @Time:2021年4月25日下午12:19:59
 */
public class Test {
	public static void main(String[] args) throws IOException {
		//利用jsoup爬取文本内容
		//指定网络资源地址
		String urlHtml = "https://www.hbsi.edu.cn/xygk/xyjj.htm";
		//通过jsoup获取Document对象
		Document document = Jsoup.connect(urlHtml).post();
		//通过属性匹配获取爬取的文本内容
		Elements text = document.getElementsByAttributeValue("id", "vsb_content_501");
		//打印文本,arraylist
		System.out.println(text.eachText());
		//打印html
		System.out.println(text.html());
		//打印第一个找到的元素
		System.out.println(text.first());
		//包装好的方法有很多,一试就会
	}
}
3.3.批量爬取网络图片
package com.Li.Jsoup.img;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @Description: 利用jsoup 实现  批量爬取图片
 * @auther:Li Ya Hui
 * @Time:2021年4月25日下午1:55:52
 */
public class Test {
	public static void main(String[]  args) throws IOException {
		String url 
						

上一篇: 实操干货!用Java记录媒体视频的播放进度

下一篇: 合并多个MP4视频文件的Java方法