欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java爬取豆瓣電影示例解析

 更新時(shí)間:2020年07月17日 11:55:29   作者:代碼忘煩惱  
這篇文章主要介紹了java爬取豆瓣電影示例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

為什么我們要爬取數(shù)據(jù)

在大數(shù)據(jù)時(shí)代,我們要獲取更多數(shù)據(jù),就要進(jìn)行數(shù)據(jù)的挖掘、分析、篩選,比如當(dāng)我們做一個(gè)項(xiàng)目的時(shí)候,需要大量真實(shí)的數(shù)據(jù)的時(shí)候,就需要去某些網(wǎng)站進(jìn)行爬取,有些網(wǎng)站的數(shù)據(jù)爬取后保存到數(shù)據(jù)庫(kù)還不能夠直接使用,需要進(jìn)行清洗、過濾后才能使用,我們知道有些數(shù)據(jù)是非常真貴的。

分析豆瓣電影網(wǎng)站

我們使用Chrome瀏覽器去訪問豆瓣的網(wǎng)站如

https://movie.douban.com/explore#!type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20&page_start=0

在Chrome瀏覽器的network中會(huì)得到如下的數(shù)據(jù)


可以看到地址欄上的參數(shù)type=movie&tag=熱門&sort=recommend&page_limit=20&page_start=0

其中type是電影tag是標(biāo)簽,sort是按照熱門進(jìn)行排序的,page_limit是每頁(yè)20條數(shù)據(jù),page_start是從第幾頁(yè)開始查詢。

但是這不是我們想要的,我們需要去找豆瓣電影數(shù)據(jù)的總?cè)肟诘刂肥窍旅孢@個(gè)https://movie.douban.com/tag/#/

我們?cè)俅蔚娜ピL問請(qǐng)求終于拿到了豆瓣的電影數(shù)據(jù)如下圖所示


在看下請(qǐng)求頭信息


最后我們確認(rèn)了爬取的入口為:https://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=0

創(chuàng)建Maven項(xiàng)目開始爬取

我們創(chuàng)建一個(gè)maven工程,如下圖所示

maven工程的依賴,這里只是爬取數(shù)據(jù),所以沒有必要使用Spring,這里使用的數(shù)據(jù)持久層框架是mybatis 數(shù)據(jù)庫(kù)用的是mysql,下面是maven的依賴

<dependencies>
 <dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20160810</version>
 </dependency>

 <dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.47</version>
 </dependency>

 <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.47</version>
 </dependency>

 <dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.1</version>
 </dependency>

 <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
 </dependency>
 </dependencies>

創(chuàng)建好之后,結(jié)構(gòu)如下所示

首先我們?cè)趍odel包中建立實(shí)體對(duì)象,字段和豆瓣電影的字段一樣,就是請(qǐng)求豆瓣電影的json對(duì)象里面的字段


Movie實(shí)體類

public class Movie {

 private String id; //電影的id
 private String directors;//導(dǎo)演
 private String title;//標(biāo)題
 private String cover;//封面
 private String rate;//評(píng)分
 private String casts;//演員


 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getDirectors() {
  return directors;
 }

 public void setDirectors(String directors) {
  this.directors = directors;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getCover() {
  return cover;
 }

 public void setCover(String cover) {
  this.cover = cover;
 }

 public String getRate() {
  return rate;
 }

 public void setRate(String rate) {
  this.rate = rate;
 }

 public String getCasts() {
  return casts;
 }

 public void setCasts(String casts) {
  this.casts = casts;
 }
}

這里注意的是導(dǎo)演和演員是多個(gè)人我沒有直接處理。這里應(yīng)該是一個(gè)數(shù)組對(duì)象。

創(chuàng)建mapper接口

public interface MovieMapper {

 void insert(Movie movie);
 
 List<Movie> findAll();
}

在resources下創(chuàng)建數(shù)據(jù)連接配置文件jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/huadi
username=root
password=root

創(chuàng)建mybatis配置文件 mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 <properties resource="jdbc.properties"></properties>
 <environments default="development">
  <environment id="development">
   <transactionManager type="JDBC"/>
   <dataSource type="POOLED">
    <property name="driver" value="${driver}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
   </dataSource>
  </environment>
 </environments>
 <mappers>
  <mapper resource="MovieMapper.xml"/>
 </mappers>
</configuration>

創(chuàng)建mapper.xml映射文件

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cn.scitc.mapper.MovieMapper">
 <resultMap id="MovieMapperMap" type="com.cn.scitc.model.Movie">
  <id column="id" property="id" jdbcType="VARCHAR"/>
  <id column="title" property="title" jdbcType="VARCHAR"/>
  <id column="cover" property="cover" jdbcType="VARCHAR"/>
  <id column="rate" property="rate" jdbcType="VARCHAR"/>
  <id column="casts" property="casts" jdbcType="VARCHAR"/>
  <id column="directors" property="directors" jdbcType="VARCHAR"/>

 </resultMap>

 <insert id="insert" keyProperty="id" parameterType="com.cn.scitc.model.Movie">
  INSERT INTO movie(id,title,cover,rate,casts,directors)
  VALUES
  (#{id},#{title},#{cover},#{rate},#{casts},#{directors})
 </insert>
 <select id="findAll" resultMap="MovieMapperMap">
  SELECT * FROM movie
 </select>
</mapper>

由于這里沒有用任何的第三方爬蟲框架,用的是原生Java的Http協(xié)議進(jìn)行爬取的,所以我寫了一個(gè)工具類

public class GetJson {
 public JSONObject getHttpJson(String url, int comefrom) throws Exception {
  try {
   URL realUrl = new URL(url);
   HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
   connection.setRequestProperty("accept", "*/*");
   connection.setRequestProperty("connection", "Keep-Alive");
   connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
   // 建立實(shí)際的連接
   connection.connect();
   //請(qǐng)求成功
   if (connection.getResponseCode() == 200) {
    InputStream is = connection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //10MB的緩存
    byte[] buffer = new byte[10485760];
    int len = 0;
    while ((len = is.read(buffer)) != -1) {
     baos.write(buffer, 0, len);
    }
    String jsonString = baos.toString();
    baos.close();
    is.close();
    //轉(zhuǎn)換成json數(shù)據(jù)處理
    // getHttpJson函數(shù)的后面的參數(shù)1,表示返回的是json數(shù)據(jù),2表示http接口的數(shù)據(jù)在一個(gè)()中的數(shù)據(jù)
    JSONObject jsonArray = getJsonString(jsonString, comefrom);
    return jsonArray;
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException ex) {
   ex.printStackTrace();
  }
  return null;
 }

 public JSONObject getJsonString(String str, int comefrom) throws Exception{
  JSONObject jo = null;
  if(comefrom==1){
   return new JSONObject(str);
  }else if(comefrom==2){
   int indexStart = 0;
   //字符處理
   for(int i=0;i<str.length();i++){
    if(str.charAt(i)=='('){
     indexStart = i;
     break;
    }
   }
   String strNew = "";
   //分割字符串
   for(int i=indexStart+1;i<str.length()-1;i++){
    strNew += str.charAt(i);
   }
   return new JSONObject(strNew);
  }
  return jo;
 }

}

爬取豆瓣電影的啟動(dòng)類

public class Main {
 public static void main(String [] args) {

  String resource = "mybatis-config.xml"; 定義配置文件路徑
  InputStream inputStream = null;
  try {
   inputStream = Resources.getResourceAsStream(resource);//讀取配置文件
  } catch (IOException e) {
   e.printStackTrace();
  }

  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//注冊(cè)mybatis 工廠

  SqlSession sqlSession = sqlSessionFactory.openSession();//得到連接對(duì)象

  MovieMapper movieMapper = sqlSession.getMapper(MovieMapper.class);//從mybatis中得到dao對(duì)象

  int start;//每頁(yè)多少條
  int total = 0;//記錄數(shù)
  int end = 9979;//總共9979條數(shù)據(jù)
  for (start = 0; start <= end; start += 20) {
   try {

    String address = "https://Movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start=" + start;

    JSONObject dayLine = new GetJson().getHttpJson(address, 1);

     System.out.println("start:" + start);
     JSONArray json = dayLine.getJSONArray("data");
     List<Movie> list = JSON.parseArray(json.toString(), Movie.class);

     if (start <= end){
      System.out.println("已經(jīng)爬取到底了");
      sqlSession.close();
     }
     for (Movie movie : list) {
      movieMapper.insert(movie);
      sqlSession.commit();
     }
     total += list.size();
     System.out.println("正在爬取中---共抓取:" + total + "條數(shù)據(jù)");

   } catch (Exception e) {
    e.printStackTrace();
   }

  }
 }

}

最后我們運(yùn)行將所有的數(shù)據(jù)插入到數(shù)據(jù)庫(kù)中。

項(xiàng)目地址

github

總結(jié)

爬取豆瓣網(wǎng)站非常的輕松,每頁(yè)任何的難度,需要注意的是就是start是每頁(yè)多少條我們發(fā)現(xiàn)規(guī)則當(dāng)start=0的時(shí)候是20條數(shù)據(jù)是從0到19條,就這樣每次加20條直到爬取完。

到此這篇關(guān)于java爬取豆瓣電影示例解析的文章就介紹到這了,更多相關(guān)java爬取豆瓣電影內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java中的匿名對(duì)象定義與用法實(shí)例分析

    Java中的匿名對(duì)象定義與用法實(shí)例分析

    這篇文章主要介紹了Java中的匿名對(duì)象定義與用法,結(jié)合實(shí)例形式分析了java匿名對(duì)象的概念、原理、定義與相關(guān)使用注意事項(xiàng),需要的朋友可以參考下
    2019-08-08
  • logback StatusListener的定義方法源碼解讀

    logback StatusListener的定義方法源碼解讀

    這篇文章主要為大家介紹了logback StatusListener的定義方法源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11
  • Java常用的時(shí)間類以及其轉(zhuǎn)化方式

    Java常用的時(shí)間類以及其轉(zhuǎn)化方式

    這篇文章主要介紹了Java常用的時(shí)間類以及其轉(zhuǎn)化方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • 使用Feign調(diào)用第三方http接口

    使用Feign調(diào)用第三方http接口

    這篇文章主要介紹了使用Feign調(diào)用第三方http接口,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • knife4j?整合?springboot的過程詳解

    knife4j?整合?springboot的過程詳解

    這篇文章主要介紹了knife4j整合springboot的過程,本次整合springboot版本為2.3.12,本文通過圖文實(shí)例相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-09-09
  • Mybatis全局配置及映射關(guān)系的實(shí)現(xiàn)

    Mybatis全局配置及映射關(guān)系的實(shí)現(xiàn)

    本文主要介紹了Mybatis全局配置及映射關(guān)系的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • java類中生成jfreechart,返回圖表的url地址 代碼分享

    java類中生成jfreechart,返回圖表的url地址 代碼分享

    這篇文章介紹了java類中生成jfreechart,返回圖表的url地址的代碼,有需要的朋友可以參考一下
    2013-08-08
  • Java使用POI導(dǎo)出Excel(一):?jiǎn)蝧heet

    Java使用POI導(dǎo)出Excel(一):?jiǎn)蝧heet

    這篇文章介紹了Java使用POI導(dǎo)出Excel的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-10-10
  • Mybatis 入門示例代碼之 Association

    Mybatis 入門示例代碼之 Association

    這篇文章主要介紹了Mybatis 入門示例代碼之 Association,需要的的朋友參考下
    2017-02-02
  • SpringBoot中Tomcat和SpringMVC整合源碼分析

    SpringBoot中Tomcat和SpringMVC整合源碼分析

    Tomcat和SpringMVC都是通過這樣的方式進(jìn)行集成的,SpringBoot出現(xiàn)之前SpringMVC項(xiàng)目是直接部署在Tomcat服務(wù)器中的,這篇文章主要介紹了SpringBoot中Tomcat和SpringMVC整合源碼分析,需要的朋友可以參考下
    2022-07-07

最新評(píng)論