python多进程爬取上海房价并画出热力图分析

一、分析目的

1.探索上海市的房价区域分布

2.看看购房者都喜欢购买哪里的房子

二、数据采集

采集我爱我家上海区域的一万两千个小区的数据,采集的字段有小区、位置、最近30条成交套数、在售、在租、成交均价、成交总价、小区详细介绍等数据。直接上代码:

import requests,codecs

import pymongo,time

from lxml import html

from multiprocessing import Pool

def get_content(j):

    print('正在爬取第{}页,还剩{}页'.format(j,561-j))

    url='https://sh.5i5j.com/xiaoqu/n{}/_?zn='.format(j)

    r=requests.get(url)

    r=html.fromstring(r.text)

    lenth=len(r.xpath('//ul[@class="pList"]/li'))

    try:

        for i in range(1,lenth):

            urls=r.xpath('//ul[@class="pList"]/li[{0}]/div[2]/h3/a/@href'.format(i))[0]

            community=r.xpath('//ul[@class="pList"]/li[{0}]/div[2]/h3/a/text()'.format(i))[0]

            deal=r.xpath('//ul[@class="pList"]/li[{0}]//div[2]/div[1]/p[1]/span[1]/a/text()'.format(i))[0]

            onsale=r.xpath('//ul[@class="pList"]/li[{0}]//div[2]/div[1]/p[1]/span[2]/a/text()'.format(i))[0].replace('\r','').replace('\n','').strip()

            rent=r.xpath('//ul[@class="pList"]/li[{0}]//div[2]/div[1]/p[1]/span[3]/a/text()'.format(i))[0].replace('\r','').replace('\n','').strip()

            #addr=r.xpath('//ul[@class="pList"]/li[{0}]/div[2]/div[1]/p[3]/text()'.format(i))[0].replace('\r','').replace('\n','').strip()

            avgprice=r.xpath('//ul[@class="pList"]/li[{0}]//div[2]/div[1]/div/p[1]/strong/text()'.format(i))[0]

            totalprice=r.xpath('//ul[@class="pList"]/li[{0}]//div[2]/div[1]/div/p[2]/text()'.format(i))[0]

            output="{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format(community,deal,onsale,rent,avgprice,totalprice,urls)

            savetoexcel(output)

    except Exception as e:

        print(e)

        print('爬取失败')

def savetoexcel(output):

    try:

        f=codecs.open('house.xls','a+','utf-8')

        f.write(output)

        f.close()

    except Exception as e:

        print('写入失败')

if __name__ == '__main__':

    pool=Pool(processes=2)

    pool.map(get_content,list(range(1,561)))

    pool.close()

    pool.join()


采集下来是这个样子的:

image

接着利用高德API把小区转换为经纬度坐标,这个代码就不贴了。转换之后变成这样:

image

三、数据可视化

利用百度地图API生成热力图。


* * *

<!DOCTYPE html>

<html>

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ie1pboEhSttv7biL1iYj6kUI"></script>

    <script type="text/javascript" src="http://api.map.baidu.com/library/Heatmap/2.0/src/Heatmap_min.js"></script>

    <title>热力图功能示例</title>

    <style type="text/css">

ul,li{list-style: none;margin:0;padding:0;float:left;}

html{height:100%}

body{height:100%;margin:0px;padding:0px;font-family:"微软雅黑";}

#container{height:500px;width:100%;}

#r-result{width:100%;}

    </style>

</head>

<body>

<div id="container"></div>

<div id="r-result">

<input type="button"  onclick="openHeatmap();" value="显示热力图"/><input type="button"  onclick="closeHeatmap();" value="关闭热力图"/>

</div>

</body>

</html>

<script type="text/javascript">

    var map = new BMap.Map("container");          // 创建地图实例

    var point = new BMap.Point(121.409868, 31.208977);

    map.centerAndZoom(point, 15);            // 初始化地图,设置中心点坐标和地图级别

    map.enableScrollWheelZoom(); // 允许滚轮缩放

    var points =[

{"lng":121.524245,"lat":31.234472,"count":5},

{"lng":121.525868,"lat":31.225027,"count":10},

{"lng":121.439535,"lat":31.133423,"count":5},

{"lng":121.511138,"lat":31.231639,"count":1}

];

    if(!isSupportCanvas()){

    alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')

    }

//详细的参数,可以查看heatmap.js的文档 https://github.com/pa7/heatmap.js/blob/master/README.md

//参数说明如下:

/* visible 热力图是否显示,默认为true

    * opacity 热力的透明度,1-100

    * radius 势力图的每个点的半径大小 

    * gradient  {JSON} 热力图的渐变区间 . gradient如下所示

    * {

.2:'rgb(0, 255, 255)',

.5:'rgb(0, 110, 255)',

.8:'rgb(100, 0, 255)'

}

其中 key 表示插值的位置, 0~1.

    value 为颜色值.

    */

heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":50});

map.addOverlay(heatmapOverlay);

heatmapOverlay.setDataSet({data:points,max:11});

//是否显示热力图

    function openHeatmap(){

        heatmapOverlay.show();

    }

function closeHeatmap(){

        heatmapOverlay.hide();

    }

closeHeatmap();

    function setGradient(){

    /*格式如下所示:

{

  0:'rgb(102, 255, 0)',

.5:'rgb(255, 170, 0)',

  1:'rgb(255, 0, 0)'

}*/

    var gradient = {};

    var colors = document.querySelectorAll("input[type='color']");

    colors = [].slice.call(colors,0);

    colors.forEach(function(ele){

gradient[ele.getAttribute("data-key")] = ele.value;

    });

        heatmapOverlay.setOptions({"gradient":gradient});

    }

//判断浏览区是否支持canvas

    function isSupportCanvas(){

        var elem = document.createElement('canvas');

        return !!(elem.getContext && elem.getContext('2d'));

    }

</script>

* * *

把point里面的数据替换成自己的坐标,修改一下半径和最大值,保存到本地,修改成index.html,放到容易找到的位置,然后利用python搭载简易的服务器,在cmd命令窗口,cd到index.html对应文件夹,然后输入

python -m http.server 80

接着用浏览器打开http://localhost:80

就可以看到热力图了。来看看最近30天成交的房子都是哪里的:

image

可以看出最近成交的房子主要集中在黄浦江旁边,看来大家都比较喜欢靠近江边的房子,房子成交最多的是闵行莘庄一带(估计是房价稍微便宜点)和浦东的外滩附近(估计是金融从业人士购买力比较强)。

接下来看看房价分布。本来想直接6000多个小区的经纬度导入,结果百度地图API无法生存热力图,汗,,试试999个,还是不行,我晕。。。那就每个区域选择40个小区作为代表了,下面是sql语句



select a1.* from sheet1 a1

inner join

(select a.区域,a.均价 from sheet1 a left join sheet1 b

on a.区域=b.区域 and a.均价<=b.均价

group by a.区域,a.均价

having count(b.均价)<=60

)b1

on a1.区域=b1.区域 and a1.均价=b1.均价

order by a1.区域,a1.均价 desc;

替换坐标,改一下半径和最大值,来看看结果:

image

图中颜色深的房价表示10万以上每平,,看来还是长宁静安黄埔徐汇最贵了。毕竟是市中心啊。也就看看就好,买不起啊。。。。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容