1.Jsoup简述
Java中支持的爬虫框架有很多,比如WebMagic、Spider、Jsoup等。今天我们使用Jsoup来实现一个简单的爬虫程序。
?Jsoup拥有十分方便的api来处理html文档,比如参考了DOM对象的文档遍历方法,参考了CSS选择器的用法等等,因此我们可以使用Jsoup快速地掌握爬取页面数据的技巧。
2.快速开始
1)编写HTML页面
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<table>
<thead>
<tr>
<td>商品名字</td>
<td>商品图片</td>
</tr>
</thead>
<tbody>
<tr>
<td class="pname">product1</td>
<td class="pimg"><img src="img/1.bmp"/></td>
</tr>
<tr>
<td class="pname">product2</td>
<td class="pimg"><img src="img/2.bmp"/></td>
</tr>
</tbody>
</table>
</body>
</html>
页面中表格的商品信息是我们要爬取的数据。其中属性pname类的商品名称,以及属于pimg类的商品图片。
2)使用HttpClient读取HTML页面
HttpClient是一个处理Http协议数据的工具,使用它可以将HTML页面作为输入流读进java程序中。可以从http://hc.apache.org/下载HttpClient的jar包。
//获得HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
//定义要爬取数据的目标页面url
String url = "http://localhost:8080/MyShop/shop.jsp";
//使用HttpGet对象绑定url
HttpGet httpGet = new HttpGet(url);
//访问url获得响应消息封装在HttpResponse对象中
HttpResponse httpResponse = httpClient.execute(httpGet);
//entity中是响应消息的实体
HttpEntity entity = httpResponse.getEntity();
//使用EntityUtils的toString获得url指定页面的字符串内容,即html本身
String html = EntityUtils.toString(entity);
System.out.println(html);
3)使用Jsoup解析html字符串
通过引入Jsoup工具,直接调用parse方法来解析一个描述html页面内容的字符串来获得一个Document对象。该Document对象以操作DOM树的方式来获得html页面上指定的内容。相关API可以参考Jsoup官方文档:https://jsoup.org/cookbook/
下面我们使用Jsoup来获取上述html中指定的商品名称和价格的信息。
//JSOUP解析页面数据,获得Document对象
Document doc = Jsoup.parse(html);
//在Document对象的select方法中使用选择器来获得指定的元素,该选择器与CSS及Jquery的选择器相同。
Elements eles = doc.select("table tbody tr .pname");
Element ele = eles.get(0);
//获得指定元素的文本内容
System.out.println(ele.text());
Elements ele_imgs = doc.select("table tbody img");
//获得指定元素的src属性的值
String img_src = ele_imgs.get(0).attr("src");
System.out.println(img_src);
至此,我们已经实现使用HttpClient+Jsoup爬取HTML页面数据的功能。接下来,我们让效果更直观一些,比如将爬取的数据存到数据库中,将图片存到服务器上。
3.保存爬取的页面数据
1)保存普通数据到数据库中
将爬取的数据封装进实体Bean中,并存到数据库内。
//将数据封装到Javabean中
Product p = new Product();
p.setPid(UUID.randomUUID().toString());
p.setPname(ele.text());
p.setPimg(img_src);
//将存入数据库中
ProductDao dao = new ProductDao();
try {
dao.addProduct(p);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//dao的操作
public void addProduct(Product p) throws SQLException {
QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
String sql = "insert into product values(?,?,?)";
qr.update(sql,p.getPid(),p.getPname(),p.getPimg());
}
2)保存图片到服务器上
直接通过下载图片的方式将图片保存到服务器本地。
private void downloadImg(HttpServletRequest request,Product p) throws ClientProtocolException, IOException {
//获得图片的原url
String url = "http://localhost:8080"+p.getPimg();
//使用HttpClient获得图片资源
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
//获得请求的图片资源的输入流
InputStream is = httpResponse.getEntity().getContent();
//在服务器本地创建文件,用于接收图片
String img_name = p.getPimg().substring(p.getPimg().lastIndexOf("/")+1);
String realPath = request.getRealPath("/Download/"+img_name);
File dir = new File(request.getRealPath("/Download"));
if(!dir.exists()){
//如果文件夹不存在,则创建
dir.mkdirs();
}
//读写数据,保存图片
File file = new File(realPath);
FileOutputStream fos = new FileOutputStream(file);
int b = 0;
while((b = is.read())!=-1){
fos.write(b);
}
fos.close();
}
4.总结
本案简单实现了使用HttpClient+Jsoup爬取网络数据,对于爬虫技术本身,还有很多值得深挖的地方,以后再为大家讲解。