使用JSoup實現簡單的爬蟲技術

1.Jsoup簡述

Java中支持的爬蟲框架有很多,比如WebMagic、Spider、Jsoup等。今天我們使用Jsoup來實現一個簡單的爬蟲程序。

​Jsoup擁有十分方便的api來處理html文檔,比如參考了DOM對象的文檔遍歷方法,參考了CSS選擇器的用法等等,因此我們可以使用Jsoup快速地掌握爬取頁面數據的技巧。

2.快速開始

1)編寫HTML頁面

Insert title here

商品名字商品圖片
product1
product2

頁面中表格的商品信息是我們要爬取的數據。其中屬性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爬取網絡數據,對於爬蟲技術本身,還有很多值得深挖的地方,以後再為大家講解。


分享到:


相關文章: