原
Java資料爬取——爬取攜程酒店資料(一)
2016年11月23日 15:29:38
賈小牛
閱讀數:8107
最近工作要收集點酒店資料,就到攜程上看了看,記錄爬取過程去下
1.根據城市名稱來分類酒店資料,是以先找了所有城市的名稱
在這個網頁上有http://hotels.ctrip.com/domestic-city-hotel.html

從網站地圖上可以很容易發現這個頁面
2.然後檢視源碼
<dl class = "pinyin_filter_detail layoutfix"></dl>
- 1
3.我們擷取一下dl 這個元素和其中的所有子元素
我們用jsoup的jar包來解析擷取的html,官網https://jsoup.org/,有API和jar包
String result = HttpUtil.getInstance().httpGet(null, "http://hotels.ctrip.com/domestic-city-hotel.html");
Document root_document = Jsoup.parse(result);
Elements pinyin_filter_elements = root_document.getElementsByClass("pinyin_filter_detail layoutfix");
//包含所有城市的Element
Element pinyin_filter = pinyin_filter_elements.first();
- 2
- 3
- 4
- 5
- 6
4.我準備把擷取的城市資料存儲到mysql中,是以下面連接配接了本地mysql資料庫
// 連接配接資料庫
Connection conn = SqlDBUtils.getConnection();
StringBuilder create_table_sql = new StringBuilder();
create_table_sql.append("create table if not exists ctrip_hotel_city (id integer primary key auto_increment, city_id integer not null, city_name varchar(255) not null, head_pinyin varchar(80) not null, pinyin varchar(255) not null)");
PreparedStatement preparedStatement;
try {
//每次執行删除一下表,防止資料插入重複
preparedStatement = conn.prepareStatement("DROP TABLE IF EXISTS ctrip_hotel_city");
preparedStatement.execute();
// 建立ctrip_hotel_city表,存儲城市資料
preparedStatement = conn.prepareStatement(create_table_sql.toString());
preparedStatement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
5.擷取dl下所有的dt和dd,并從中提取資料庫表中所需要的字段,實作存儲
//拼音首字元Elements
Elements pinyins = pinyin_filter.getElementsByTag("dt");
//所有dd的Elements
Elements hotelsLinks = pinyin_filter.getElementsByTag("dd");
6.資料提取
for (int i = 0; i < pinyins.size(); i++) {
Element head_pinyin = pinyins.get(i);
Element head_hotelsLink = hotelsLinks.get(i);
Elements links = head_hotelsLink.children();
for (Element link : links) {
String cityId = StringUtil.getNumbers(link.attr("href"));
String cityName = link.html();
String head_pinyin_str = head_pinyin.html();
String pinyin_cityId = link.attr("href").replace("/hotel/", "");
String pinyin = pinyin_cityId.replace(StringUtil.getNumbers(link.attr("href")), "");
StringBuffer insert_sql = new StringBuffer();
insert_sql.append("insert into ctrip_hotel_city (city_id, city_name, head_pinyin, pinyin) values (");
insert_sql.append(cityId);
insert_sql.append(", '" + cityName + "'");
insert_sql.append(", '" + head_pinyin_str + "'");
//此處注意漢語拼音中會有',直接插入資料庫會報錯,要把一個'替換為兩個''
insert_sql.append(", '" + pinyin.replace("'", "''") + "')");
try {
preparedStatement = conn.prepareStatement(insert_sql.toString());
preparedStatement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
7.運作後檢視mysql資料庫
ctrip_hotel_city
表,如下