Spring Boot 慕課網爬蟲


 

一、項目簡介(Demo簡介)

  慕課網。。。打了三個字,還是不介紹了避免廣告。一個簡單爬蟲該網站的demo。

  地址:https://www.imooc.com/course/list?c=springboot

二、項目結構

   項目多層架構:common層,controller層,entity層,repository層,由於Demo比較簡單就沒有細分那么多了(偷懶)。

  

三、項目說明

F12 查看頁面html結構,發現如下

本次我只抽取了 課程名稱,url,等級,描述四個字段。

  • 數據庫,創建imooc_spider數據庫,表course。
  • JPA,這里我結合Spring boot JPA,application.yml配置如下。創建對應的CourseEntiy
  •  


  • @Entity @Table(name = "course") public class CourseEntity { @Id @GeneratedValue private Integer id; private String name; private String url; private String desc; private String level; }

      

  • 解析html。http請求這里就不介紹了,重點就是解析html,采用Jsoup,當然也可以使用正則,但是我覺得Jsoup比較直觀方便操作。解析的代碼要結合頁面上的html。
  • div[class=clearfix] 代表頁面 <div class="clearfix">
    如果直接<div class="clearfix"> 會提示找不到改節點
  • package com.jet.imoocspider.common;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.jet.imoocspider.entity.CourseEntity;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import org.jsoup.select.Elements;
    
    public class HtmlParse {
    
        public static List<CourseEntity> getData (String html) throws Exception{
            //獲取的數據,存放在集合中
            List<CourseEntity> data = new ArrayList<CourseEntity>();
            //采用Jsoup解析
            Document doc = Jsoup.parse(html);
            //獲取html標簽中的內容
            Elements elements=doc.select("div[class=clearfix]").select("div[class=course-card-container]").select("a[class=course-card]");
            for (Element ele:elements) {
                String url="https://www.imooc.com".concat(ele.attr("href"));
                String name=ele.select("div[class=courseEntity-card-content]").select("h3[class=courseEntity-card-name]").html();
                Elements elementLevelParent=ele.select("div[class=courseEntity-card-content]").select("div[class=clearfix courseEntity-card-bottom]");
                String level=elementLevelParent.select("div[class=courseEntity-card-info]").tagName("span").first().text();
                String desc=elementLevelParent .select("p[class=courseEntity-card-desc]").text();
    
                CourseEntity courseEntity =new CourseEntity();
                courseEntity.setDesc(desc);
                courseEntity.setUrl(url);
                courseEntity.setName(name);
                courseEntity.setLevel(level);
    
    
                //將每一個對象的值,保存到List集合中
                data.add(courseEntity);
            }
            //返回數據
            return data;
        }
    }
    

     

  •  

     

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM