python爬虫租房信息在地图上显示的方法
人气:0本人初学python是菜鸟级,写的不好勿喷。
python爬虫用了比较简单的urllib.parse和requests,把爬来的数据显示在地图上。接下里我们话不多说直接上代码:
1.安装python环境和编辑器(自行度娘)
2.本人以58品牌公寓为例,爬取在杭州地区价格在2000-4000的公寓。
#-*- coding:utf-8 -*- from bs4 import BeautifulSoup from urllib.parse import urljoin import requests import csv import time
以上是需要引入的模块
url = "http://hz.58.com/pinpaigongyu/pn/{page}/?minprice=2000_4000" #已完成的页数序号,初时为0 page = 0
以上的全局变量
csv_file = open(r"c:\users\****\Desktop\houoseNew.csv","a+",newline='') csv_writer = csv.writer(csv_file, delimiter=',')
自定义某个位置来保存爬取得数据,本人把爬取得数据保存为csv格式便于编辑(其中”a+”表示可以多次累加编辑在后面插入数据,建议不要使用“wb”哦!newline=”表示没有隔行)
while True: #为了防止网站屏蔽ip,设置了时间定时器每隔5秒爬一下。打完一局农药差不多都爬取过来了。 time.sleep(5) page +=1 #替换URL中page变量 print (url.format(page=page)+"ok") response = requests.get(url.format(page=page)) html=BeautifulSoup(response.text) #寻找html中DOM节点li house_list = html.select(".list > li") # 循环在读不到新的房源时结束 if not house_list: break for house in house_list: #根据hml的DOM节点获取自己需要的数据 house_title = house.select("h2")[0].string house_url = urljoin(url, house.select("a")[0]["href"]) house_pic = urljoin(url, house.select("img")[0]["lazy_src"]) house_info_list = house_title.split() # 如果第一列是公寓名 则取第二列作为地址 if "公寓" in house_info_list[0] or "青年社区" in house_info_list[0]: house_location = house_info_list[0] else: house_location = house_info_list[1] house_money = house.select(".money")[0].select("b")[0].string csv_writer.writerow([house_title, house_location, house_money,house_pic ,house_url]) #最后不要忘记关闭节流 csv_file.close()
如果网站屏蔽了你的ip,你可以做一个ip地址数组放在http的头部具体度娘一下吧。
接下来我们写html
只是简单的写了一下写的不好见谅。用的是高德地图,具体的js api可以到高德开发者上去看。
<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)"/> 地铁 <input type="radio" name="vehicle" value="WALK" onClick="takeWalk(this)"/> 走路 <input type="radio" name="vehicle" value="BIKE" onClick="takeBike(this)"/> 骑车 </div> </div> <div class="control-entry"> <label>导入房源文件:</label> <div class="control-input"> <input type="file" name="file" id="fileCsv"/> <button style="margin-top: 10px;width: 50%;" onclick="changeCsv()">开始</button> </div> </div> </div> <div id="transfer-panel"></div> <script> var map = new AMap.Map("container", { resizeEnable: true, zoomEnable: true, center: [120.1256856402492, 30.27289264553506], zoom: 12 }); //添加标尺 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({ //通过id指定输入元素 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 takeWalk(radio){ vehicle = radio.value; loadWorkLocation() } function takeBike(radio) { vehicle = radio.value; loadWorkLocation() } //获取加载的文件 function changeCsv() { $("#fileCsv").csv2arr(function (res) { $.each(res, function (k, p) { if (res[k][1]) { //addMarkerByAddress(地址,价格,展示的图片) addMarkerByAddress(res[k][1], res[k][2],res[k][3]) } }) }); } function workLocationSelected(e) { workAddress = e.poi.name; loadWorkLocation(); } 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, money,imgUrl) { var geocoder = new AMap.Geocoder({ city: "杭州", radius: 1000 }); geocoder.getLocation(address, function (status, result) { var iconValue = ""; var _money=money; if (money.indexOf("-") > -1) { _money = money.split("-")[1]; } //如果价格高于3000元/月在地图上显示红色,低于的话显示蓝色 if (parseFloat(_money) > 3000) { iconValue="http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png"; }else{ iconValue = "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png"; } if (status === "complete" && result.info === 'OK') { var geocode = result.geocodes[0]; rentMarker = new AMap.Marker({ map: map, title: address, icon:iconValue, animation:"AMAP_ANIMATION_DROP", position: [geocode.location.getLng(), geocode.location.getLat()] }) ; rentMarkerArray.push(rentMarker); //鼠标点击标记显示相应的内容 rentMarker.content = "<img src='"+imgUrl+"'/><div>房源:<a target = '_blank' href='http://bj.58.com/pinpaigongyu/?key=" + address + "'>" + address + "</a><p>价格:"+money+"</p><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); //加载60分钟内工作地点到达圈 loadWorkRange(x, y, 60, "#3f67a5", vehicle); //地图移动到工作地点的位置 map.setZoomAndCenter(12, [x, y]); } }) } </script> </body>
想要获取完整的代码github:https://github.com/DIVIBEAR/pythonDemo.git
新手上路,老司机们勿喷!
以上所述是小编给大家介绍的python爬虫租房信息在地图上显示的方法详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
您可能感兴趣的文章:
加载全部内容