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()

 

采集下来是这个样子的:

 

python多进程爬取上海房价并画出热力图分析_第1张图片

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

python多进程爬取上海房价并画出热力图分析_第2张图片

三、数据可视化

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




    
    
    
    
    热力图功能示例
    	


	

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

python -m http.server 80

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

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

python多进程爬取上海房价并画出热力图分析_第3张图片

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

接下来看看房价分布。本来想直接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;

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

python多进程爬取上海房价并画出热力图分析_第4张图片

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

你可能感兴趣的:(Python,数据分析)