記:本項目是在實驗樓上看到的,但是上面的代碼由於沒有及時維護,爬蟲文件的代碼不再能完整的把所有房源信息爬取下來,我根據最新的58同城官網進行了研究,現在的官網的房源信息已經不是分頁的了,而是拉到最後自動進行加載,所以一些地方的代碼也需要做一些修改。其次是爬取出來的文件在偶數行是空行的問題也得到了解決,在打開文件的時候添加一個參數即可。目前未解決的問題時字體加密問題,於是我刪掉了money參數,僅供參考,後期有時間再研究字體加密怎麼解決。希望得到大佬的在線指教。。。
1、摘要:
利用一些開放平臺的API可以很方便的進行編程,早在考研時期就面臨找房困難、房源信息混亂以及不清楚房源周邊的交通情況。近期在跟廖雪峯老師學習python的過程中看到有類似的項目,在學習了該項目之後,也想把鄭州的房源根據價格區間爬取出房源信息存儲到csv文件中,然後利用高德地圖的API接口進行位置上的標識和交通路線的規劃。
2、最終的結果圖:
3、實現流程圖:
本項目主要有三個文件,分別是:crawl.py、rent2.csv、index.html。其中用到的幾個API文檔爲:高德地圖JavaScript API幫助文檔和示例中心、Requests:Http for Humans、Beautiful Soup 4.2.0文檔。
crawl.py:爬蟲腳本,用來爬取房源信息
Rent2.csv:由crawl.py生成的房源信息文件
Index.html:地圖顯示房源和路徑規劃文件
要爬取的房源網站:https://zz.58.com/pinpaigongyu
4、爬取房源實現
(1)分析要爬取的頁面發現網站路徑規律應該爲:/pinpaigongyu/?minprice={min_price}_{max_price},因爲現在的58網站沒有分頁設置,直接是拉到最後自動進行加載,所以去掉了分頁參數。
(2)找到房源信息列表,以list元素爲標記,循環訪問list元素裏每一個li元素中的房源信息,提取出有效的房源信息。
(3)編寫爬蟲腳本文件:由於運行腳本文件後,爬取的時間間隔較小,原房源網站會彈出確認窗口,此時按規定進行確認,之後再重新進行爬取。
from bs4 import BeautifulSoup
import requests
import csv
import time
import lxml
url = "https://zz.58.com/pinpaigongyu/?minprice=1000_2000"
csv_file = open("rent2.csv","w",newline="",encoding='utf-8')
csv_writer = csv.writer(csv_file, delimiter=',')
while True:
print("fetch: ", url)
time.sleep(2)
response = requests.get(url)
html = BeautifulSoup(response.text,features="lxml")
house_list = html.select(".list > li")
# 循環在讀不到新的房源時結束
if not house_list:
break
for house in house_list:
house_title = house.select("h2")[0].string.strip()
house_url = house.select("a")[0]["href"]
house_info_list = house_title.split()
# 如果第二列是公寓名則取第一列作爲地址
if "公寓" in house_info_list[1] or "青年社區" in house_info_list[1]:
house_location = house_info_list[0]
else:
house_location = house_info_list[1]
csv_writer.writerow([house_title, house_location, house_url])
csv_file.close()
5、調用高德地圖API:
直接在高德地圖API示例中心把要用的地圖的前端框架複製下來,在根據示例和手冊對API中的方法進行調用,在這裏主要是閱讀高德地圖的示例和參考手冊。在使用高德地圖的API之前需要先擁有一個key,在加載地圖的時候使用。
完整代碼:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>畢業生租房</title>
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css" />
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/jquery.range.css" />
<script src="http://cache.amap.com/lbs/static/jquery-1.9.1.js"></script>
<script src="http://cache.amap.com/lbs/static/es5.min.js"></script>
<script src="http://webapi.amap.com/maps?v=1.3&key=651b94b986317c1e68d082ec56773eb5&plugin=AMap.ArrivalRange,AMap.Scale,AMap.Geocoder,AMap.Transfer,AMap.Autocomplete"></script>
<script src="http://cache.amap.com/lbs/static/jquery.range.js"></script>
<style>
.control-panel {
position: absolute;
top: 30px;
right: 20px;
}
.control-entry {
width: 280px;
background-color: rgba(119, 136, 153, 0.8);
font-family: fantasy, sans-serif;
text-align: left;
color: white;
overflow: auto;
padding: 10px;
margin-bottom: 10px;
}
.control-input {
margin-left: 120px;
}
.control-input input[type="text"] {
width: 160px;
}
.control-panel label {
float: left;
width: 120px;
}
/* 路徑規劃面板 */
#transfer-panel {
position: absolute;
background-color: white;
max-height: 80%;
overflow-y: auto;
top: 30px;
left: 20px;
width: 250px;
}
</style>
</head>
<body>
<div id="container"></div>
<div class="control-panel">
<div class="control-entry">
<label>選擇工作地點:</label>
<div class="control-input">
<input id="work-location" type="text">
</div>
</div>
<div class="control-entry">
<label>選擇通勤方式:</label>
<div class="control-input">
<input type="radio" name="vehicle" value="SUBWAY,BUS" onClick="takeBus(this)" checked/> 公交+地鐵
<input type="radio" name="vehicle" value="SUBWAY" onClick="takeSubway(this)" /> 地鐵
</div>
</div>
<div class="control-entry">
<label>導入房源文件:</label>
<div class="control-input">
<input type="file" name="file" onChange="importRentInfo(this)" />
</div>
</div>
</div>
<div id="transfer-panel"></div>
<script>
// 地圖初始化城市和地圖的一些屬性
var map = new AMap.Map("container", {
resizeEnable: true,
zoomEnable: true,
center: [113.65, 34.7],
zoom: 11
});
// 添加標尺
var scale = new AMap.Scale();
map.addControl(scale);
var arrivalRange = new AMap.ArrivalRange(); //公交到達圈
var x, y, t, vehicle = "SUBWAY,BUS"; //經緯度和交通方式
var workAddress, workMarker; //工作地點和工作標記
var rentMarkerArray = []; //房源標記隊列
var polygonArray = []; //多邊形隊列,存儲公交到達的計算結果
var amapTransfer; //路徑規劃
// 信息窗體對象
var infoWindow = new AMap.InfoWindow({
offset: new AMap.Pixel(0, -30)
});
// 地址自動補全對象
var auto = new AMap.Autocomplete({
input: "work-location"
});
// 在選擇完地址後自動調用worklocationselected方法
AMap.event.addListener(auto, "select", workLocationSelected);
function takeBus(radio) {
vehicle = radio.value;
loadWorkLocation()
}
function takeSubway(radio) {
vehicle = radio.value;
loadWorkLocation()
}
// 觸發房源信息
function importRentInfo(fileInfo) {
var file = fileInfo.files[0].name;
loadRentLocationByFile(file);
}
function workLocationSelected(e) {
workAddress = e.poi.name;
loadWorkLocation(); //調用加載1小時內到達的區域方法
}
// 工作地點標記(標記爲紅色)
function loadWorkMarker(x, y, locationName) {
workMarker = new AMap.Marker({
map: map,
title: locationName,
icon: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
position: [x, y]
});
}
// 加載範圍域
function loadWorkRange(x, y, t, color, v) {
arrivalRange.search([x, y], t, function(status, result) {
if (result.bounds) {
for (var i = 0; i < result.bounds.length; i++) {
var polygon = new AMap.Polygon({
map: map,
fillColor: color,
fillOpacity: "0.4",
strokeColor: color,
strokeOpacity: "0.8",
strokeWeight: 1
});
polygon.setPath(result.bounds[i]);
polygonArray.push(polygon);
}
}
}, {
policy: v
});
}
function addMarkerByAddress(address) {
var geocoder = new AMap.Geocoder({
city: "鄭州",
radius: 1000
});
geocoder.getLocation(address, function(status, result) {
if (status === "complete" && result.info === 'OK') {
var geocode = result.geocodes[0];
rentMarker = new AMap.Marker({
map: map,
title: address,
icon: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
position: [geocode.location.getLng(), geocode.location.getLat()]
});
rentMarkerArray.push(rentMarker);
rentMarker.content = "<div>房源:<a target = '_blank' href='https://zz.58.com/pinpaigongyu/?key=" + address + "'>" + address + "</a><div>"
rentMarker.on('click', function(e) {
infoWindow.setContent(e.target.content);
infoWindow.open(map, e.target.getPosition());
if (amapTransfer) amapTransfer.clear();
amapTransfer = new AMap.Transfer({
map: map,
policy: AMap.TransferPolicy.LEAST_TIME,
city: "鄭州市",
panel: 'transfer-panel'
});
amapTransfer.search([{
keyword: workAddress
}, {
keyword: address
}], function(status, result) {})
});
}
})
}
function delWorkLocation() {
if (polygonArray) map.remove(polygonArray);
if (workMarker) map.remove(workMarker);
polygonArray = [];
}
function delRentLocation() {
if (rentMarkerArray) map.remove(rentMarkerArray);
rentMarkerArray = [];
}
function loadWorkLocation() {
delWorkLocation();
var geocoder = new AMap.Geocoder({
city: "鄭州",
radius: 1000
});
geocoder.getLocation(workAddress, function(status, result) {
if (status === "complete" && result.info === 'OK') {
var geocode = result.geocodes[0];
x = geocode.location.getLng();
y = geocode.location.getLat();
loadWorkMarker(x, y);
loadWorkRange(x, y, 60, "#3f67a5", vehicle);
map.setZoomAndCenter(12, [x, y]);
}
})
}
// 加載房源位置
function loadRentLocationByFile(fileName) {
delRentLocation();
var rent_locations = new Set();
$.get(fileName, function(data) {
data = data.split("\n");
data.forEach(function(item, index) {
rent_locations.add(item.split(",")[1]);
});
rent_locations.forEach(function(element, index) {
addMarkerByAddress(element); //爲房源添加標記
});
});
}
</script>
</body>
</html>
6、項目演示步驟和效果:
在終端輸入python -m http.server 3000啓動服務器,然後在瀏覽器輸入http://localhost:3000查看效果,在右上角的panel中輸入工作地點,交通方式,房源信息文件查看效果。