使用beautifulsoup包爬取链家网徐汇地区的房价
首先导入需要使用的包

点进链家网站,选择徐汇地区,发现网页地址为‘https://sh.lianjia.com/ershoufang/xuhui/pg1’
所以先定义两个函数,一个是输入‘https://sh.lianjia.com/ershoufang/xuhui/’,自动获取N页的地址。

F12打开网页开发者工具,发现每个房子的次级页面是在class为‘info clear’的div里,用request包中的Request向网页发送请求,然后用urlopen打开请求,最后用Beautiful对网页进行解析。


下面是爬取网页的主程序,我们需要爬取的是房价、房屋位置、房屋名字、房屋户型。
定义url='https://sh.lianjia.com//ershoufang//xuhui//'。定义headers信息。先获取到100页的徐汇区房价网址。

爬取信息并且写入csv文件,首先打开一个csv文件,准备写入。遍历每个子页面并且对子页面进行解析,并且将信息写入p,hi,name几个列表。

上面程序中的loc=getlocation(name[n])是调用了一个百度api接口,在上面定义了一个getlocation函数,输入小区的位置可以获取小区的精度和纬度。

接下来就是把数据写入字典。

最后得到了一个house字典,导出整合成网页热力图需要的格式,放入html文件中,生成热力图。

热力图中越红的区域代表房价越高。
可见越靠近地铁沿线房价越高,尤其是一号线。
网友评论