简单JAVA爬虫51Jobs
使用Jsoup工具,它是一个HTML解析器,可以直接直接解析某个地址或者HTML文件。还可 通过Dom,CSS以及类似JQuery的操作方法操作数据。
Jsoup官方文档地址:https://jsoup.org/cookbook/introduction/parsing-a-document
注意:出现乱码时,需要查看编码方式网页的编码方式,使用它的编码方式解码。使用表单传输中文数据时有些网站需要进行url编码才能正常传输中文=。=
主要代码如下:
package com.galoliy.spider.maven_spider.domain; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; public class Cat5jobs { public Document getResultPage(String url,String keyword) throws UnsupportedEncodingException {
Document doc = null; //multipart/form-data 编码类型转换,必须进行转换,不然会导致POST里的keyword乱码
//Multipart/form-data code type conversion must be converted, otherwise it will cause keyword confusion in POST.
keyword = URLEncoder.encode(keyword, "gbk"); try { //获取主页
//Get index page
Response resp = Jsoup.connect(url).method(Method.GET).execute();
doc = resp.parse(); //获取查询结果页的跳转链接
//Get query results jump page link
String actionPath = doc.select("form").attr("action"); Connection con = Jsoup.connect(actionPath)
.data("keyword", keyword)
.userAgent("Mozilla")
.cookies(resp.cookies())
.header("Accept-Language", "zh-CN,zh;q=0.9")
.timeout(300000);
//得到查询结果页面
//Get query results page
doc = con.method(Method.POST).execute().parse(); } catch (IOException e) {
e.printStackTrace();
}
return doc;
} public void getResult(String url,String keyword,String dir,String fileName) { Document doc = null;
File htmlPath = null;
File txtPath = null;
String htmlFilePath = dir + fileName + ".htm";
String txtFilePath = dir + fileName + "2.txt";
txtPath = new File(txtFilePath);
htmlPath = new File(htmlFilePath);
Map map = null;
String printSrc = ""; try {
//本地如果有html文件则解析该文件,打印内容并储存一个txt文件
//If there is a HTML file in the local area, parse the file, print the contents and store a TXT file.
if(!txtPath.exists() && htmlPath.exists()) { doc = Jsoup.parse(htmlPath, "utf-8"); if(!doc.children().isEmpty())
System.out.println("File not empty"); map = Screen51Jobs(doc);
printSrc = printScreen(map);
saveFile(printSrc, txtFilePath);
System.out.println(printSrc); //如果本地有html和txt文件则读取txt文件内容,否则抛出IOException
//If you have HTML and txt files locally, you can read the contents of the txt file, otherwise throw IOException.
}else if(txtPath.exists() && htmlPath.exists()) {
System.out.println("File not empty");
printSrc = printScreen(txtPath);
System.out.println(printSrc);
}else
throw new IOException("NOT HTML FILE"); } catch (IOException e) { //在catch块里执行爬虫并且把文件保存在本地,Execute crawler in catch block and save the file locally. System.out.println("file not found"); try { //从网址上获取查询结果页面
//Get query results page from web address
doc = this.getResultPage(url,keyword); htmlPath.createNewFile();
//存储html文件
//Save html file
saveFile(doc.toString(),htmlFilePath); map = Screen51Jobs(doc);
String printStr = printScreen(map); if(!htmlPath.exists())
htmlPath.createNewFile();
//存储txt文件
//Save txt file
saveFile(printStr, txtFilePath); System.out.println(printSrc); } catch (IOException ex) {
ex.printStackTrace();
}
} } private String printScreen(File path) throws IOException{ StringBuilder printSrc = new StringBuilder();
InputStream in = new FileInputStream(path);
BufferedInputStream bis = new BufferedInputStream(in); int len = 0;
byte[] bytes = new byte[1024 * 8];
while((len = bis.read(bytes, 0, bytes.length)) != -1) {
printSrc.append(new String(bytes,0,bytes.length));
}
bis.close(); return printSrc.toString();
} private String printScreen(Map<?,?> screen) throws IOException { StringBuilder sb = new StringBuilder();
String p = "\r\n";
sb.append(p + " KeyWord:" + screen.get("keyword") + p + p +" Total query data:"
+ screen.get("totalquerydata") + p + p + " Recruitment info:"); List list = (ArrayList)screen.get("recruitmentlist"); for (Object o : list) {
Map map = (HashMap<String,Object>)o; for (Object obj : map.entrySet()) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>)obj;
sb.append(p + entry.getKey() + " == " + entry.getValue());
}
sb.append(p);
} return sb.toString();
} @SuppressWarnings({ "rawtypes", "unchecked" })
private Map<?,?> Screen51Jobs(Document doc){ Map screen = new HashMap<String,Object>(); Elements resultList = doc.select("div[class=dw_table]div[id=resultList]");
Elements findKeyword = resultList.select("div[class=sbox]");
Elements totalQueryData = resultList.select("div[class=rt]div:matchesOwn(^共)");
Elements recruitmentInfo = resultList.select("div[class=el]"); screen.put("keyword", findKeyword.text());
screen.put("totalquerydata", totalQueryData.text()); List recruitmentList = new ArrayList<Map<String,String>>();
Map m = null;
for (Element e : recruitmentInfo) {
m = new HashMap<String,Object>();
m.put("position",e.select("p[class~=^t1]").text());
m.put("href", e.select("a").attr("href"));
m.put("corporatename", e.select("a").text());
m.put("address", e.select("span[class=t3]").text());
m.put("salary", e.select("span[class=t4]").text());
m.put("releasedate", e.select("span[class=t5]").text());
recruitmentList.add(m);
}
screen.put("recruitmentlist", recruitmentList); return screen;
} private void saveFile(String src,String path) throws IOException { // InputStream in = new FileInputStream(path);
OutputStream out = new FileOutputStream(path);
BufferedOutputStream bos = new BufferedOutputStream(out); byte[] bytes = src.getBytes("utf-8"); bos.write(bytes, 0, bytes.length);
}
简单JAVA爬虫51Jobs的更多相关文章
- 一个简单java爬虫爬取网页中邮箱并保存
		此代码为一十分简单网络爬虫,仅供娱乐之用. java代码如下: package tool; import java.io.BufferedReader; import java.io.File; im ... 
- 超简单的java爬虫
		最简单的爬虫,不需要设定代理服务器,不需要设定cookie,不需要http连接池,使用httpget方法,只是为了获取html代码... 好吧,满足这个要求的爬虫应该是最基本的爬虫了.当然这也是做复杂 ... 
- java简单web爬虫(网页图片)
		java简单web爬虫(网页图片)效果,执行main()方法后图片就下载道C盘的res文件夹中.没有的话创建一个文件夹代码里的常量根据自己的需求修改,代码附到下面. package com.sinit ... 
- 学校实训作业:Java爬虫(WebMagic框架)的简单操作
		项目名称:java爬虫 项目技术选型:Java.Maven.Mysql.WebMagic.Jsp.Servlet 项目实施方式:以认知java爬虫框架WebMagic开发为主,用所学java知识完成指 ... 
- webmagic的设计机制及原理-如何开发一个Java爬虫
		之前就有网友在博客里留言,觉得webmagic的实现比较有意思,想要借此研究一下爬虫.最近终于集中精力,花了三天时间,终于写完了这篇文章.之前垂直爬虫写了一年多,webmagic框架写了一个多月,这方 ... 
- JAVA爬虫 WebCollector
		JAVA爬虫 WebCollector 爬虫简介: WebCollector是一个无须配置.便于二次开发的JAVA爬虫框架(内核),它提供精简的的API,只需少量代码即可实现一个功能强大的爬虫. 爬虫 ... 
- 爬虫入门  手写一个Java爬虫
		本文内容 涞源于 罗刚 老师的 书籍 << 自己动手写网络爬虫一书 >> ; 本文将介绍 1: 网络爬虫的是做什么的? 2: 手动写一个简单的网络爬虫; 1: 网络爬虫是做 ... 
- JAVA爬虫实践(实践三:爬虫框架webMagic和csdnBlog爬虫)
		WebMagic WebMagic是一个简单灵活的Java爬虫框架.基于WebMagic,你可以快速开发出一个高效.易维护的爬虫. 采用HttpClient可以实现定向的爬虫,也可以自己编写算法逻辑来 ... 
- java爬虫系列第一讲-爬虫入门
		1. 概述 java爬虫系列包含哪些内容? java爬虫框架webmgic入门 使用webmgic爬取 http://ady01.com 中的电影资源(动作电影列表页.电影下载地址等信息) 使用web ... 
随机推荐
- Django高级篇三。restful的解析器,认证组件,权限组件
			一.rest=framework之解析器 1)解析器作用. 根据提交的数据.只解析某些特定的数据.非法数据不接收,为了系统安全问题 比如解析的数据格式有 有application/json,x-www ... 
- iOS 开发之 KVC - setValuesForKeysWithDictionary 解析
			从字典映射到一个对象,这是KVC中的一个方法所提供的,这个方法就是 setValuesForKeysWithDictionary:,非常好用,不需要你来一一的给对象赋值而直接从字典初始化即可,但用的不 ... 
- js将数组根据条件分组
			//将数组根据条件分组 function getTreeDateByParam(list, param, fun){ var data = {}; if(list && list.le ... 
- s5 Docker的持久化存储和数据共享
			数据库容器的数据如何才能不会丢失?Docker的持久化存储技术.Docker的数据共享技术能极大提高开发人员的开发效率,边写代码,边看运行结果. 数据持久化之Data Volume Docker持久化 ... 
- 源码分析MySQL mysql_real_query函数
			目录 目录 1 1. 前言 1 2. 调用路径 2 3. MAX_PACKET_LENGTH宏 2 4. DBUG_RETURN宏 3 5. COM_QUERY枚举值 3 6. mysql_query ... 
- jmeter+Jenkins持续集成(邮件通知)
			jmeter构建后,自送发送邮件到指定的邮箱,配置如下 1)Jenkins Location配置 jenkins首页->系统管理->系统配置页面 其中Jenkins URL有默认值,最好修 ... 
- verilog HDL-并行语句之assign
			线网型数据对象: 是verilog hdl常用数据对象之一,起到电路节点之间的互联作用,类似于电路板上的导线. wire是verilog hdl默认的线网型数据对象. 线网型数据对象的读操作在代码任何 ... 
- Android 音乐(音效)播放方式总结
			一.音效的分类 音效按照作用的不同,可以将音效分为即时音效和背景音乐.两种音效在Android中的实现技术是不同的. 主要的实现方式为:SoundPool.MediaPlayer. 区别在于,Medi ... 
- 第二十三节:Java语言基础-详细讲解函数与数组
			函数 函数在Java中称为方法,在其他语言中可能称为函数,函数,方法就是定义在类中具有特定功能的程序.函数,在Java中可称为方法. 函数的格式: 修饰符 返回值类型 函数名(参数类型 参数1, 参数 ... 
- MySQL学习笔记1(增删查改)
			创建表: /* 创建数据库 create database 数据库名; */ CREATE DATABASE mybase; /* 使用数据库 use 数据库名 */ USE mybase; /* 创 ... 
