java爬取豆瓣電影示例解析
為什么我們要爬取數(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)行清洗、過(guò)濾后才能使用,我們知道有些數(shù)據(jù)是非常真貴的。
分析豆瓣電影網(wǎng)站
我們使用Chrome瀏覽器去訪問(wèn)豆瓣的網(wǎng)站如
在Chrome瀏覽器的network中會(huì)得到如下的數(shù)據(jù)

可以看到地址欄上的參數(shù)type=movie&tag=熱門(mén)&sort=recommend&page_limit=20&page_start=0
其中type是電影tag是標(biāo)簽,sort是按照熱門(mén)進(jìn)行排序的,page_limit是每頁(yè)20條數(shù)據(jù),page_start是從第幾頁(yè)開(kāi)始查詢。
但是這不是我們想要的,我們需要去找豆瓣電影數(shù)據(jù)的總?cè)肟诘刂肥窍旅孢@個(gè)https://movie.douban.com/tag/#/
我們?cè)俅蔚娜ピL問(wèn)請(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)目開(kāi)始爬取
我們創(chuàng)建一個(gè)maven工程,如下圖所示

maven工程的依賴,這里只是爬取數(shù)據(jù),所以沒(méi)有必要使用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è)人我沒(méi)有直接處理。這里應(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>
由于這里沒(méi)有用任何的第三方爬蟲(chóng)框架,用的是原生Java的Http協(xié)議進(jìn)行爬取的,所以我寫(xiě)了一個(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)目地址
總結(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動(dòng)態(tài)代理的兩種實(shí)現(xiàn)方式(JDK/Cglib)
本篇文章主要介紹了java動(dòng)態(tài)代理的兩種實(shí)現(xiàn)方式,詳細(xì)的介紹了JDK和Cglib的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,有興趣的可以了解一下2017-04-04
使用 Java 開(kāi)發(fā) Gradle 插件的步驟
這篇文章主要介紹了使用 Java 開(kāi)發(fā) Gradle 插件的步驟,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下2021-03-03
MyBatis通用Mapper實(shí)現(xiàn)原理及相關(guān)內(nèi)容
今天小編就為大家分享一篇關(guān)于MyBatis通用Mapper實(shí)現(xiàn)原理及相關(guān)內(nèi)容,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
Lucene實(shí)現(xiàn)多種高級(jí)搜索形式
這篇文章主要介紹了Lucene實(shí)現(xiàn)多種高級(jí)搜索形式的相關(guān)資料,需要的朋友可以參考下2017-04-04
SpringBoot?Security從入門(mén)到實(shí)戰(zhàn)示例教程
Spring?Security是一個(gè)功能強(qiáng)大且高度可定制的身份驗(yàn)證和訪問(wèn)控制框架,接下來(lái)通過(guò)本文給大家介紹SpringBoot?Security從入門(mén)到實(shí)戰(zhàn)示例教程,感興趣的朋友一起看看吧2022-05-05
Java如何遠(yuǎn)程調(diào)用對(duì)方接口
這篇文章主要介紹了Java如何遠(yuǎn)程調(diào)用對(duì)方接口問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
java實(shí)現(xiàn)基于UDP協(xié)議的聊天小程序操作
UDP是與TCP相對(duì)應(yīng)的協(xié)議,UDP適用于一次只傳送少量數(shù)據(jù)、對(duì)可靠性要求不高的應(yīng)用環(huán)境。正因?yàn)閁DP協(xié)議沒(méi)有連接的過(guò)程,所以它的通信效率高;但也正因?yàn)槿绱?,它的可靠性不如TCP協(xié)議高,本文給大家介紹java實(shí)現(xiàn)基于UDP協(xié)議的聊天小程序操作,感興趣的朋友一起看看吧2021-10-10
MyBatis圖文并茂講解注解開(kāi)發(fā)一對(duì)一查詢
這篇文章主要介紹了SpringBoot中Mybatis注解一對(duì)一查詢的實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Java8實(shí)現(xiàn)任意參數(shù)的鏈棧
這篇文章主要為大家詳細(xì)介紹了Java8實(shí)現(xiàn)任意參數(shù)的鏈棧,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-10-10

