二手房网站信息数据分析、数据可视化-基于python的crawl,jupyter notebook进行数据清洗和可视化。

爬取数据

使用的是beautifulsoup和request库,最终将数据存入excel即csv格式
首先导入库:

import requests
from bs4 import BeautifulSoup
import csv

创建一个方法-根据网页链接和headers获取网页的内容:

def crawl_data(crawl_url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 Edg/90.0.818.62'
    }

    url = 'https://sh.lianjia.com' + crawl_url
    try:
        response = requests.get(url, headers=headers)
        start(response)
    except Exception as e:
        print(e)

抓取二手房的相关信息 包括描述、位置、房子信息、补充信息、价格、单位价格、标签
注意:用soup爬取所有最外层li的时候,class是clear LOGVIEWDATA LOGCLICKDATA;原因见此链接:原因

def start(response):
    item = {}
    soup = BeautifulSoup(response.text,'html.parser')
    contentlist=soup.find_all('li',{'class':'clear LOGVIEWDATA LOGCLICKDATA'})
    print(contentlist)

    for con in contentlist:
        describe=con.find('div',{'class':'title'}).text
        position=con.find('div',{'class','positionInfo'}).text
        houseinfo=con.find('div',{'class':'houseInfo'}).text
        followinfo=con.find('div',{'class':'followInfo'}).text
        cost=con.find('div',{'class':'totalPrice'}).find('span').text
        unitcost=con.find('div',{'class':'unitPrice'}).find('span').text
        tag=con.select('div.tag > span')
        totaltag = ''
        for t in tag:
            totaltag+=str(t.text) +','
        link=con.find('div',{'class':'title'}).find('a').get('href')
        seller,sellerscore,sellerreply=getseller(link)

        item = {"describe":describe,
                "position":position,
                "houseinfo":houseinfo,
                "followinfo":followinfo,
                "cost":cost,
                "unitcost":unitcost,
                "totaltag":totaltag,
                "seller":seller,
                "sellerscore":sellerscore,
                "sellerreply":sellerreply}
        print(item)
        item_list.append(item)

由于销售员在另一个页面,因此要先爬取销售员所在界面的url,再爬取此url的信息。在此getseller中传入的link参数就是上面代码块中:“link=con.find(‘div’,{‘class’:‘title’}).find(‘a’).get(‘href’)”爬到的url

def getseller(link):
    headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 Edg/90.0.818.62'}
    resp=requests.get(link,headers=headers)
    soupl = BeautifulSoup(resp.text, 'html.parser')
    seller = soupl.find('div', {'class': 'brokerName'}).find('a').text
    sellerinfo=soupl.select('div.evaluate > span')
    sellerscore=(sellerinfo[0].text)[3:]
    sellerreply=((sellerinfo[-1].text)[1:])[:-3]
    return seller,sellerscore,sellerreply

def一个函数写入csv的表头:

def csv_title():
    return['标题','位置','房屋信息','关注人数及发布时间','总价','每平米价格','所有标签','销售者','销售者评分','关于销售者的评论']

main函数。这里爬取了20页,所以range(20),放在循环里依次加一。
最后是将所有爬取信息写入csv(遍历item_list)。

if __name__=='__main__':
    start_url = '/ershoufang/'
    item_list = []
    for a in range(20):
        next='/ershoufang/pg'
        next_url = next+str(a+1)+'/'
        print(next_url)
        crawl_data(next_url)
    file_name='链家信息爬取.csv'
    with open(file_name,'w',newline='',encoding='utf-8-sig') as f:
        pen=csv.writer(f)
        pen.writerow(csv_title())
        for i in item_list:
            pen.writerow(i.values())
    print("爬取完成,共爬取%d条数据"% len(item_list))

最终爬取出信息存入excel中,这个样子:
在这里插入图片描述

然后爬虫部分就结束了。

数据清洗

下边是利用jupyter notebook进行数据清洗,把一些不需要的信息用代码去除。
把一些关键的代码放在这里,完整的jupyter代码文件我会上传。
用了pandas和numpy库。

这里是取前500条数据:

df.drop(df.index[500:],inplace=True)

将位置细分,分为地址区域和详细地址两部分。

df['详细地址']=df['位置'].str.split('-',expand=True)[0]
df['地址区域']=df['位置'].str.split('-',expand=True)[1]

多了最后两列:
在这里插入图片描述

基本就是分片、将信息细分。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

数据可视化

接下来是数据的可视化。引用了这些库、字体。

import pandas as pd
import numpy as np
import collections

import matplotlib.pyplot as plt
import seaborn as sns
import wordcloud
import jieba

plt.rcParams['font.sans-serif']=['FangSong']
plt.rcParams['axes.unicode_minus']=False

用matplot库完成普普通通总价饼状图:

total_prices = list(df["总价"])

total_prices_count = collections.Counter(total_prices)
 
total_prices_count = total_prices_count.most_common(10)
total_prices_dic = {k: v for k, v in total_prices_count}
 
total_prices = sorted(total_prices_dic)
counts = [total_prices_dic[k] for k in total_prices]
 
plt.pie(total_prices,labels=total_prices,autopct='%1.2f%%')
 
plt.title("链家房源总价Top10", fontsize=20)
 
plt.savefig('test1.PNG')

plt.show()

在这里插入图片描述

将文本中词语出现的频率作为一个参数绘制词云图:
jieba–分词
wordcloud–词云

word_counts=list(df["标题"])
word = len(list(jieba.cut(str(word_counts), cut_all=False)))
from matplotlib.pyplot import imread
bg_pic = imread('爱心.jpg')
plt.imshow(bg_pic) 
wordlist=''
for item in word_counts:
    wordlist+=item[0]+' '
wc = wordcloud.WordCloud(
        width=2000, 
        height=800, 
        font_path='simhei.ttf',                         
        background_color="white",                         
        max_words=1000,                                 
        max_font_size=50,       
        mask=bg_pic,   
    )

wc.generate(wordlist)               
wc.to_file('big.jpg')
plt.imshow(wc)                                           
plt.axis('off')                                        

plt.savefig('test3.PNG')
plt.show()     

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

!!!注意:以上代码是在2021年5月完成的,现在不确定是否还能无差错爬取,如果链家网站之后有了变化,可以根据新的class名称进行爬取。
爬虫、数据清洗、数据可视化的思路分享给大家。

  • 8
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
要实现Python爬取链家二手房数据可视化,可以按照以下步骤进行操作: 1. 使用Scrapy框架进行分布式爬取链家二手房的数据。Scrapy是一个强大的Python爬虫框架,可以帮助我们快速高效地爬取网页数据。可以使用Scrapy编写爬虫程序,设置爬取的起始URL和相关的爬取规则,然后通过分布式爬取多个页面的数据。 2. 将爬取到的数据存储到MySQL数据库中。可以使用Python的MySQL库连接到MySQL数据库,并将爬取到的数据存储到数据库中。可以创建一个表来存储二手房的相关信息,例如房源名称、价格、面积等。 3. 使用pandas进行数据清洗和分析。pandas是一个强大的数据处理和分析库,可以帮助我们对爬取到的数据进行清洗和分析。可以使用pandas读取MySQL数据库中的数据,并进行数据清洗、处理和分析,例如去除重复数据、处理缺失值、计算统计指标等。 4. 使用可视化进行数据可视化Python有很多强大的可视化库,例如matplotlib、seaborn和plotly等。可以使用这些库来绘制各种图表,例如柱状图、折线图、散点图等,以展示二手房数据的分布、趋势和关联性。 以下是一个示例代码,演示了如何使用Scrapy爬取链家二手房的数据,并使用pandas和matplotlib进行数据清洗可视化: ```python import scrapy import pandas as pd import matplotlib.pyplot as plt class LianjiaSpider(scrapy.Spider): name = 'lianjia' start_urls = ['https://www.lianjia.com/ershoufang/'] def parse(self, response): # 解析页面数据,提取二手房信息 # ... # 将数据存储到MySQL数据库中 # ... yield item # 使用命令行运行爬虫 # scrapy crawl lianjia # 从MySQL数据库读取数据 data = pd.read_sql('SELECT * FROM lianjia', 'mysql://username:password@localhost/lianjia') # 数据清洗和分析 # ... # 绘制柱状图 plt.bar(data['区域'], data['价格']) plt.xlabel('区域') plt.ylabel('价格') plt.title('链家二手房价格分布') plt.show() ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值