爬取两万多租房数据,告诉你广州房租现状

开发 后端 数据分析
,早就有挺多小伙伴叫我分析一下广州的租房价格现状,这不,文章就这样在众多呼声中出炉了。然后,此次爬虫技术也升级了,完善了更多细节。源码值得细细探究。

概述

  • 前言
  • 统计结果
  • 爬虫代码实现
  • 爬虫分析实现
  • 后记

前言

建议在看这篇文章之前,请看完这三篇文章,因为本文是依赖于前三篇文章的:

  • 爬虫利器初体验(1)
  • 听说你的爬虫又被封了?(2)
  • 爬取数据不保存,就是耍流氓(3)

八月份的时候,由于脑洞大开,决定用 python 爬虫爬取了深圳的租房数据,并写了文章《用Python告诉你深圳房租有多高》,文章得到了一致好评和众多转载。由于我本身的朋友圈大多都在广州、深圳,因此,早就有挺多小伙伴叫我分析一下广州的租房价格现状,这不,文章就这样在众多呼声中出炉了。然后,此次爬虫技术也升级了,完善了更多细节。源码值得细细探究。此次分析采集了广州 11 个区,23339 条数据,如下图: 

爬取两万多租房数据,告诉你广州房租现状

样本数据

 

其中后半部分地区数据量偏少,是由于该区房源确实不足。因此,此次调查也并非非常准确,权且当个娱乐项目,供大家观赏。

统计结果

我们且先看统计结果,然后再看技术分析。

广州房源分布:(按区划分)

其中天河占据了大部分房源。但这块地的房租可是不菲啊。 

爬取两万多租房数据,告诉你广州房租现状

房源分布

 

房租单价:(每月每平方米单价 -- 平均数)

即是 1 平方米 1 个月的价格。方块越大,代表价格越高。 

爬取两万多租房数据,告诉你广州房租现状

房租单价:平方米/月

 

可以看出天河、越秀、海珠都越过了 50 大关,分别是 75.042 、64.249、59.621 ,是其他地区的几倍。如果在天河租个 20 平方的房间:

  • 75.042 x 20 = 1500.84

再来个两百的水电、物业:

  • 1500.84 + 200 = 1700.84

我们按正常生活来算的话,每天早餐 10 块,中午 15 块,晚饭 15 块:

  • 1700.84 + 40 x 30 = 2900.84

那么平时的日常生活需要 2900.84 块。

隔断时间下个馆子,每个月买些衣服,交通费,谈个女朋友,与女朋友出去逛街,妥妥滴加个 2500

  • 2900.84 + 2500 = 5400.84

给爸妈一人一千:

  • 5200.84 + 2000 = 7200.84

月薪一万还是有点存款的,比深圳好一点,但是可能广州的薪资就没深圳那么高了。

房租单价:(每日每平方米单价 -- 平均数)

即是 1 平方米 1 天的价格。 

爬取两万多租房数据,告诉你广州房租现状

租房单价:平方米/日

 

哈哈,感受一下***的感觉。[捂脸]
户型

户型主要以 3 室 2 厅与 2 室 2 厅为主。与小伙伴抱团租房是***的选择了,不然与不认识的人一起合租,可能会发生一系列让你不舒服的事情。字体越大,代表户型数量越多。 

爬取两万多租房数据,告诉你广州房租现状

户型
爬取两万多租房数据,告诉你广州房租现状
户型

 

租房面积统计

其中 30 - 90 平方米的租房占大多数,如今之计,也只能是几个小伙伴一起租房,抱团取暖了。 

爬取两万多租房数据,告诉你广州房租现状

租房面积统计

 

租房描述词云

这是爬取的租房描述,其中字体越大,标识出现的次数越多。其中【住家、全套、豪华、齐全】占据了很大的部分,说明配套设施都是挺齐全的。 

爬取两万多租房数据,告诉你广州房租现状

租房描述

 

爬虫技术分析

  • 请求库:scrapy、requests
  • HTML 解析:BeautifulSoup
  • 词云:wordcloud
  • 数据可视化:pyecharts
  • 数据库:MongoDB
  • 数据库连接:pymongo

爬虫代码实现

跟上一篇文章不一样,这是使用了 scrapy 爬虫框架来爬取数据,各个方面也进行了优化,例如:自动生成各个页面的地址。

由于房某下各个区域的首页地址和首页以外的地址的形式是不一样的,但是又一定的规律,所以需要拼接各个部分的地址。

首页地址案例:

  1. # ***页 
  2. http://gz.zu.fang.com/house-a073/ 

非首页地址:

  1. # 第二页 
  2. http://gz.zu.fang.com/house-a073/i32/ 
  3. # 第三页 
  4. http://gz.zu.fang.com/house-a073/i33/ 
  5. # 第四页 
  6. http://gz.zu.fang.com/house-a073/i34/ 

 爬取两万多租房数据,告诉你广州房租现状

 爬取两万多租房数据,告诉你广州房租现状

先解析首页 url

  1. def head_url_callback(self, response): 
  2.     soup = BeautifulSoup(response.body, "html5lib"
  3.     dl = soup.find_all("dl", attrs={"id""rentid_D04_01"})  # 获取各地区的 url 地址的 dl 标签 
  4.     my_as = dl[0].find_all("a")  # 获取 dl 标签中所有的 a 标签, 
  5.     for my_a in my_as: 
  6.         if my_a.text == "不限":  # 不限地区的,特殊处理 
  7.             self.headUrlList.append(self.baseUrl) 
  8.             self.allUrlList.append(self.baseUrl) 
  9.             continue 
  10.         if "周边" in my_a.text:  # 清除周边地区的数据 
  11.             continue 
  12.         # print(my_a["href"]) 
  13.         # print(my_a.text) 
  14.         self.allUrlList.append(self.baseUrl + my_a["href"]) 
  15.         self.headUrlList.append(self.baseUrl + my_a["href"]) 
  16.     print(self.allUrlList) 
  17.     url = self.headUrlList.pop(0) 
  18.     yield Request(url, callback=self.all_url_callback, dont_filter=True

再解析非首页 url

这里先获取到各个地区一共有多少页,才能拼接具体的页面地址。

爬取两万多租房数据,告诉你广州房租现状

  1. 再根据头部 url 拼接其他页码的url 
  2. ef all_url_callback(self, response): # 解析并拼接所有需要爬取的 url 地址 
  3.    soup = BeautifulSoup(response.body, "html5lib"
  4.    div = soup.find_all("div", attrs={"id""rentid_D10_01"})  # 获取各地区的 url 地址的 dl 标签 
  5.    span = div[0].find_all("span")  # 获取 dl 标签中所有的 span 标签, 
  6.    span_text = span[0].text 
  7.    for index in range(int(span_text[1:len(span_text) - 1])): 
  8.        if index == 0: 
  9.            pass 
  10.            # self.allUrlList.append(self.baseUrl + my_a["href"]) 
  11.        else
  12.            if self.baseUrl == response.url: 
  13.                self.allUrlList.append(response.url + "house/i3" + str(index + 1) + "/"
  14.                continue 
  15.            self.allUrlList.append(response.url + "i3" + str(index + 1) + "/"
  16.    if len(self.headUrlList) == 0: 
  17.        url = self.allUrlList.pop(0) 
  18.        yield Request(url, callback=self.parse, dont_filter=True
  19.    else
  20.        url = self.headUrlList.pop(0) 
  21.        yield Request(url, callback=self.all_url_callback, dont_filter=True

***解析一个页面的数据

  1. def parse(self, response): # 解析一个页面的数据 
  2.     self.logger.info("=========================="
  3.     soup = BeautifulSoup(response.body, "html5lib"
  4.     divs = soup.find_all("dd", attrs={"class""info rel"})  # 获取需要爬取得 div 
  5.     for div in divs: 
  6.         ps = div.find_all("p"
  7.         try:  # 捕获异常,因为页面中有些数据没有被填写完整,或者被插入了一条广告,则会没有相应的标签,所以会报错 
  8.             for index, p in enumerate(ps):  # 从源码中可以看出,每一条 p 标签都有我们想要的信息,故在此遍历 p 标签, 
  9.                 text = p.text.strip() 
  10.                 print(text)  # 输出看看是否为我们想要的信息 
  11.             roomMsg = ps[1].text.split("|"
  12.             area = roomMsg[2].strip()[:len(roomMsg[2]) - 1] 
  13.             item = RenthousescrapyItem() 
  14.             item["title"] = ps[0].text.strip() 
  15.             item["rooms"] = roomMsg[1].strip() 
  16.             item["area"] = int(float(area)) 
  17.             item["price"] = int(ps[len(ps) - 1].text.strip()[:len(ps[len(ps) - 1].text.strip()) - 3]) 
  18.             item["address"] = ps[2].text.strip() 
  19.             item["traffic"] = ps[3].text.strip() 
  20.             if (self.baseUrl+"house/"in response.url: # 对不限区域的地方进行区分 
  21.                 item["region"] = "不限" 
  22.             else
  23.                 item["region"] = ps[2].text.strip()[:2] 
  24.             item["direction"] = roomMsg[3].strip() 
  25.             print(item) 
  26.             yield item 
  27.         except
  28.             print("糟糕,出现 exception"
  29.             continue 
  30.     if len(self.allUrlList) != 0:  
  31.         url = self.allUrlList.pop(0) 
  32.         yield Request(url, callback=self.parse, dont_filter=True

数据分析实现

这里主要通过 pymongo 的一些聚合运算来进行统计,再结合相关的图标库,来进行数据的展示。

数据分析:

  1. # 求一个区的房租单价(平方米/元) 
  2.    def getAvgPrice(self, region): 
  3.        areaPinYin = self.getPinyin(region=region) 
  4.        collection = self.zfdb[areaPinYin] 
  5.        totalPrice = collection.aggregate([{'$group': {'_id''$region''total_price': {'$sum''$price'}}}]) 
  6.        totalArea = collection.aggregate([{'$group': {'_id''$region''total_area': {'$sum''$area'}}}]) 
  7.        totalPrice2 = list(totalPrice)[0]["total_price"
  8.        totalArea2 = list(totalArea)[0]["total_area"
  9.        return totalPrice2 / totalArea2 
  10.  
  11.    # 获取各个区 每个月一平方米需要多少钱 
  12.    def getTotalAvgPrice(self): 
  13.        totalAvgPriceList = [] 
  14.        totalAvgPriceDirList = [] 
  15.        for index, region in enumerate(self.getAreaList()): 
  16.            avgPrice = self.getAvgPrice(region) 
  17.            totalAvgPriceList.append(round(avgPrice, 3)) 
  18.            totalAvgPriceDirList.append({"value": round(avgPrice, 3), "name": region + "  " + str(round(avgPrice, 3))}) 
  19.  
  20.        return totalAvgPriceDirList 
  21.  
  22.    # 获取各个区 每一天一平方米需要多少钱 
  23.    def getTotalAvgPricePerDay(self): 
  24.        totalAvgPriceList = [] 
  25.        for index, region in enumerate(self.getAreaList()): 
  26.            avgPrice = self.getAvgPrice(region) 
  27.            totalAvgPriceList.append(round(avgPrice / 30, 3)) 
  28.        return (self.getAreaList(), totalAvgPriceList) 
  29.  
  30.    # 获取各区统计样本数量 
  31.    def getAnalycisNum(self): 
  32.        analycisList = [] 
  33.        for index, region in enumerate(self.getAreaList()): 
  34.            collection = self.zfdb[self.pinyinDir[region]] 
  35.            print(region) 
  36.            totalNum = collection.aggregate([{'$group': {'_id''''total_num': {'$sum': 1}}}]) 
  37.            totalNum2 = list(totalNum)[0]["total_num"
  38.            analycisList.append(totalNum2) 
  39.        return (self.getAreaList(), analycisList) 
  40.  
  41.    # 获取各个区的房源比重 
  42.    def getAreaWeight(self): 
  43.        result = self.zfdb.rent.aggregate([{'$group': {'_id''$region''weight': {'$sum': 1}}}]) 
  44.        areaName = [] 
  45.        areaWeight = [] 
  46.        for item in result: 
  47.            if item["_id"in self.getAreaList(): 
  48.                areaWeight.append(item["weight"]) 
  49.                areaName.append(item["_id"]) 
  50.                print(item["_id"]) 
  51.                print(item["weight"]) 
  52.                # print(type(item)) 
  53.        return (areaName, areaWeight) 
  54.  
  55.    # 获取 title 数据,用于构建词云 
  56.    def getTitle(self): 
  57.        collection = self.zfdb["rent"
  58.        queryArgs = {} 
  59.        projectionFields = {'_id'False'title'True}  # 用字典指定需要的字段 
  60.        searchRes = collection.find(queryArgs, projection=projectionFields).limit(1000) 
  61.        content = '' 
  62.        for result in searchRes: 
  63.            print(result["title"]) 
  64.            content += result["title"
  65.        return content 
  66.  
  67.    # 获取户型数据(例如:3 室 2 厅) 
  68.    def getRooms(self): 
  69.        results = self.zfdb.rent.aggregate([{'$group': {'_id''$rooms''weight': {'$sum': 1}}}]) 
  70.        roomList = [] 
  71.        weightList = [] 
  72.        for result in results: 
  73.            roomList.append(result["_id"]) 
  74.            weightList.append(result["weight"]) 
  75.        # print(list(result)) 
  76.        return (roomList, weightList) 
  77.  
  78.    # 获取租房面积 
  79.    def getAcreage(self): 
  80.        results0_30 = self.zfdb.rent.aggregate([ 
  81.            {'$match': {'area': {'$gt': 0, '$lte': 30}}}, 
  82.            {'$group': {'_id''''count': {'$sum': 1}}} 
  83.        ]) 
  84.        results30_60 = self.zfdb.rent.aggregate([ 
  85.            {'$match': {'area': {'$gt': 30, '$lte': 60}}}, 
  86.            {'$group': {'_id''''count': {'$sum': 1}}} 
  87.        ]) 
  88.        results60_90 = self.zfdb.rent.aggregate([ 
  89.            {'$match': {'area': {'$gt': 60, '$lte': 90}}}, 
  90.            {'$group': {'_id''''count': {'$sum': 1}}} 
  91.        ]) 
  92.        results90_120 = self.zfdb.rent.aggregate([ 
  93.            {'$match': {'area': {'$gt': 90, '$lte': 120}}}, 
  94.            {'$group': {'_id''''count': {'$sum': 1}}} 
  95.        ]) 
  96.        results120_200 = self.zfdb.rent.aggregate([ 
  97.            {'$match': {'area': {'$gt': 120, '$lte': 200}}}, 
  98.            {'$group': {'_id''''count': {'$sum': 1}}} 
  99.        ]) 
  100.        results200_300 = self.zfdb.rent.aggregate([ 
  101.            {'$match': {'area': {'$gt': 200, '$lte': 300}}}, 
  102.            {'$group': {'_id''''count': {'$sum': 1}}} 
  103.        ]) 
  104.        results300_400 = self.zfdb.rent.aggregate([ 
  105.            {'$match': {'area': {'$gt': 300, '$lte': 400}}}, 
  106.            {'$group': {'_id''''count': {'$sum': 1}}} 
  107.        ]) 
  108.        results400_10000 = self.zfdb.rent.aggregate([ 
  109.            {'$match': {'area': {'$gt': 300, '$lte': 10000}}}, 
  110.            {'$group': {'_id''''count': {'$sum': 1}}} 
  111.        ]) 
  112.        results0_30_ = list(results0_30)[0]["count"
  113.        results30_60_ = list(results30_60)[0]["count"
  114.        results60_90_ = list(results60_90)[0]["count"
  115.        results90_120_ = list(results90_120)[0]["count"
  116.        results120_200_ = list(results120_200)[0]["count"
  117.        results200_300_ = list(results200_300)[0]["count"
  118.        results300_400_ = list(results300_400)[0]["count"
  119.        results400_10000_ = list(results400_10000)[0]["count"
  120.        attr = ["0-30平方米""30-60平方米""60-90平方米""90-120平方米""120-200平方米""200-300平方米""300-400平方米""400+平方米"
  121.        value = [ 
  122.            results0_30_, results30_60_, results60_90_, results90_120_, results120_200_, results200_300_, results300_400_, results400_10000_ 
  123.        ] 
  124.        return (attr, value) 

数据展示:

  1. # 展示饼图 
  2.    def showPie(self, title, attr, value): 
  3.        from pyecharts import Pie 
  4.        pie = Pie(title) 
  5.        pie.add("aa", attr, value, is_label_show=True
  6.        pie.render() 
  7.  
  8.    # 展示矩形树图 
  9.    def showTreeMap(self, title, data): 
  10.        from pyecharts import TreeMap 
  11.        data = data 
  12.        treemap = TreeMap(title, width=1200, height=600) 
  13.        treemap.add("深圳", data, is_label_show=True, label_pos='inside', label_text_size=19) 
  14.        treemap.render() 
  15.  
  16.    # 展示条形图 
  17.    def showLine(self, title, attr, value): 
  18.        from pyecharts import Bar 
  19.        bar = Bar(title) 
  20.        bar.add("深圳", attr, value, is_convert=False, is_label_show=True, label_text_size=18, is_random=True
  21.                # xaxis_interval=0, xaxis_label_textsize=9, 
  22.                legend_text_size=18, label_text_color=["#000"]) 
  23.        bar.render() 
  24.  
  25.    # 展示词云 
  26.    def showWorkCloud(self, content, image_filename, font_filename, out_filename): 
  27.        d = path.dirname(__name__) 
  28.        # content = open(path.join(d, filename), 'rb').read() 
  29.        # 基于TF-IDF算法的关键字抽取, topK返回频率***的几项, 默认值为20, withWeight 
  30.        # 为是否返回关键字的权重 
  31.        tags = jieba.analyse.extract_tags(content, topK=100, withWeight=False
  32.        text = " ".join(tags) 
  33.        # 需要显示的背景图片 
  34.        img = imread(path.join(d, image_filename)) 
  35.        # 指定中文字体, 不然会乱码的 
  36.        wc = WordCloud(font_path=font_filename, 
  37.                       background_color='black'
  38.                       # 词云形状, 
  39.                       mask=img, 
  40.                       # 允许***词汇 
  41.                       max_words=400, 
  42.                       # ***号字体,如果不指定则为图像高度 
  43.                       max_font_size=100, 
  44.                       # 画布宽度和高度,如果设置了msak则不会生效 
  45.                       # width=600, 
  46.                       # height=400, 
  47.                       margin=2, 
  48.                       # 词语水平摆放的频率,默认为0.9.即竖直摆放的频率为0.1 
  49.                       prefer_horizontal=0.9 
  50.                       ) 
  51.        wc.generate(text) 
  52.        img_color = ImageColorGenerator(img) 
  53.        plt.imshow(wc.recolor(color_func=img_color)) 
  54.        plt.axis("off"
  55.        plt.show() 
  56.        wc.to_file(path.join(d, out_filename)) 
  57.  
  58.    # 展示 pyecharts 的词云 
  59.    def showPyechartsWordCloud(self, attr, value): 
  60.        from pyecharts import WordCloud 
  61.        wordcloud = WordCloud(width=1300, height=620) 
  62.        wordcloud.add("", attr, value, word_size_range=[20, 100]) 
  63.        wordcloud.render() 

后记

距离上一篇租房市场的分析已经3、4 个月了,我的技术水平也得到了一定的提高。所以努力编码才是成长的捷径。***,应对外界条件的变动,我们还是应该提升自己的硬实力,这样才能提升自己的生存能力。

责任编辑:未丽燕 来源: zone7
相关推荐

2018-11-06 13:24:27

爬虫分析房租

2017-11-27 10:53:00

大数据租房数据分析

2017-11-24 12:52:01

大数据数据分析房租

2018-11-28 13:16:39

火锅数据爬虫

2018-01-04 13:29:13

租房租房网站安全

2018-08-27 09:39:33

租房数据北漂

2018-07-25 13:47:51

彭于晏邪不压正Python

2017-04-12 09:00:53

机器学习发生框架

2010-02-22 14:50:17

云计算

2018-08-27 07:01:33

数据分析数据可视化租房

2020-10-09 15:29:48

大数据国庆技术

2015-07-22 10:45:02

QQ数据大数据分析数据泄露

2021-03-12 18:09:50

大数据职业云计算

2009-04-28 08:15:33

毕业生科研

2011-08-27 13:37:15

笔记本评测

2020-07-16 11:49:49

流量焦虑移动互联网

2018-07-23 08:52:56

Python 数据获取数据处理

2017-08-21 10:05:57

Python影评 爬虫

2018-05-23 12:34:39

Python网络爬虫豆瓣电影

2016-12-22 17:01:11

点赞
收藏

51CTO技术栈公众号