1.引言
????????在過(guò)去幾十年中,房地產(chǎn)市場(chǎng)一直是全球經(jīng)濟(jì)的重要組成部分。房地產(chǎn)不僅是個(gè)人家庭的主要投資渠道,還對(duì)國(guó)家經(jīng)濟(jì)有著深遠(yuǎn)的影響。特別是,房地產(chǎn)市場(chǎng)的價(jià)格波動(dòng)對(duì)金融市場(chǎng)穩(wěn)定和宏觀經(jīng)濟(jì)政策制定產(chǎn)生了重要影響。因此,理解和預(yù)測(cè)房地產(chǎn)市場(chǎng)的價(jià)格走勢(shì)一直是研究人員和政策制定者關(guān)注的焦點(diǎn)。?然而,房地產(chǎn)市場(chǎng)的價(jià)格走勢(shì)是一個(gè)復(fù)雜而多變的問(wèn)題,受到多種因素的影響,包括經(jīng)濟(jì)周期、政策變化、地理位置和市場(chǎng)供需等。因此,需要開展深入的研究來(lái)解析這些因素如何影響房?jī)r(jià),以提供有關(guān)房地產(chǎn)市場(chǎng)未來(lái)走勢(shì)的重要見解。
? ? ? ? 爬取的房?jī)r(jià)信息網(wǎng)站為房天下(【鄭州租房網(wǎng)_鄭州租房信息|房屋出租】- 房天下 (fang.com))。
2.數(shù)據(jù)爬取
2.1導(dǎo)入必要的庫(kù):
-
requests
:用于發(fā)送HTTP請(qǐng)求以獲取網(wǎng)頁(yè)內(nèi)容。 -
BeautifulSoup
:用于解析HTML頁(yè)面。 -
numpy
:用于處理數(shù)值數(shù)據(jù)。 -
re
:用于正則表達(dá)式匹配。 -
time
:用于生成隨機(jī)延遲,以避免頻繁訪問(wèn)網(wǎng)站。 -
random
:用于生成隨機(jī)延遲時(shí)間。 -
pandas
:用于數(shù)據(jù)處理和存儲(chǔ)。
import requests
from bs4 import BeautifulSoup
import numpy as np
import re
import time
import random
2.2?定義請(qǐng)求頭部信息headers
,模擬瀏覽器請(qǐng)求,包括User-Agent和Cookie信息,以便訪問(wèn)網(wǎng)站。
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67',
'Referer':'https://zz.zu.fang.com/',
'Cookie':'改成自己的'
}
2.3?創(chuàng)建一個(gè)空的Pandas DataFrame對(duì)象data
,用于存儲(chǔ)爬取到的數(shù)據(jù),包括標(biāo)題、租房方式、布局、面積、朝向、價(jià)格和城市。
data = pd.DataFrame(columns=['標(biāo)題','租房方式','布局','面積','朝向','價(jià)格','城市'])
2.4 創(chuàng)建一個(gè)包含城市代碼的列表bar
,并定義一個(gè)城市名和城市代碼的字典city_dict
,用于城市名的映射。
bar = ['sh','gz','sz','tj','cd','cq','wuhan','suzhou','hz','nanjing','jn']
# 中英文城市名對(duì)應(yīng)關(guān)系字典
city_dict = {
'sh': '上海',
'gz': '廣州',
'sz': '深圳',
'tj': '天津',
'cd': '成都',
'cq': '重慶',
'wuhan': '武漢',
'suzhou': '蘇州',
'hz': '杭州',
'nanjing': '南京',
'jn': '濟(jì)南'
}
2.5?使用循環(huán)遍歷城市列表bar
,并在每個(gè)城市上執(zhí)行以下操作:
- 構(gòu)建URL以獲取特定城市的租房信息頁(yè)面。
- 發(fā)送HTTP請(qǐng)求以獲取頁(yè)面內(nèi)容。
- 使用Beautiful Soup解析頁(yè)面HTML。
- 使用正則表達(dá)式提取標(biāo)題、租房方式、布局、面積、朝向和價(jià)格等信息。
- 將提取的數(shù)據(jù)添加到Pandas DataFrame中。
- 在每次數(shù)據(jù)爬取后,生成隨機(jī)的延遲時(shí)間,以避免對(duì)網(wǎng)站造成過(guò)多請(qǐng)求,然后使用
time.sleep()
函數(shù)來(lái)暫停程序執(zhí)行
for j in bar:
print(f'正在爬取 {city_dict.get(j)}')
for i in range(50):
url_new = f'https://{j}.zu.fang.com/house/i3{i+2}/'
response1 = requests.get(url_new,headers=headers)
text1 = response1.text
title = re.findall('target="_blank" title="(.*?)">', text1)
zhutype = re.findall('<p class="font15 mt12 bold">\r\n (.*?)<span class="splitline">', text1)
inSale = re.findall('<span class="splitline">|</span>(.*?)<span class="splitline">|</span>.*??O<span', text1)
buju = []
mianji = []
for i in inSale:
if '室' in i or '戶' in i:
buju.append(i)
if '?' in i:
mianji.append(i[:-2])
zaox = re.findall('s="splitline">|</span>(.*?)\r\n </p>', text1)
zaox_list = []
for i in zaox:
if len(i)>2:
zaox_list.append(i.split('</span>')[-1])
jiage = re.findall('<span class="price">(.*?)</span>', text1)
for i in range(len(title)):
try:
data.loc[len(data)] = [title[i],zhutype[i],buju[i],mianji[i],zaox_list[i],jiage[i],city_dict.get(j)]
except:
# 捕獲所有類型的異常
pass
# 生成隨機(jī)的延遲時(shí)間
delay = random.uniform(0.1, 0.5)
# 暫停程序
time.sleep(delay)
2.6?最后,將所有爬取到的數(shù)據(jù)存儲(chǔ)到CSV文件房天下數(shù)據(jù).csv
中,使用data.to_csv()
方法。
data.to_csv('./房天下數(shù)據(jù).csv')
????????最終爬取了?31474 條數(shù)據(jù),數(shù)據(jù)示例如下:
3.數(shù)據(jù)可視化分析
3.1 數(shù)據(jù)導(dǎo)入預(yù)處理
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams['font.sans-serif']=['SimHei'] #用來(lái)正常顯示中文標(biāo)簽
plt.rcParams['axes.unicode_minus'] =False
data = pd.read_csv('./房天下數(shù)據(jù).csv')
data['面積'] = data['面積'].astype('int')
data['價(jià)格'] = data['價(jià)格'].astype('int')
3.2?餅圖 - 租房方式數(shù)量比較
df =data
# 計(jì)算每種租房方式的數(shù)量
rental_counts = df['租房方式'].value_counts()
# 設(shè)置餅圖
fig, ax = plt.subplots(figsize=(8, 6))
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
explode = (0.1, 0, 0, 0) # 突出顯示第一個(gè)扇區(qū)
# 創(chuàng)建餅圖
ax.pie(rental_counts, labels=rental_counts.index, autopct='%1.1f%%',
startangle=30, colors=colors, explode=explode)
# 添加標(biāo)題和圖例
ax.set_title('租房方式數(shù)量比較', fontsize=16)
ax.legend(loc='upper right')
# 顯示圖表
plt.show()
3.3?核密度估計(jì)圖 - 房屋面積分布
plt.figure(figsize=(10, 6))
sns.kdeplot(data=df, x='面積', fill=True, palette='Blues')
plt.title('房屋面積分布', fontsize=16)
plt.xlabel('面積', fontsize=12)
plt.ylabel('密度', fontsize=12)
plt.show()
3.4?柱狀圖 - 不同朝向的房屋數(shù)量比較
# 計(jì)算每個(gè)朝向的房屋數(shù)量
orientation_counts = df['朝向'].value_counts()[:6]
# 設(shè)置柱狀圖
plt.figure(figsize=(10, 6))
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
orientation_counts.plot(kind='bar', color=colors)
# 添加標(biāo)題和軸標(biāo)簽
plt.title('不同朝向的房屋數(shù)量比較', fontsize=16)
plt.xlabel('朝向', fontsize=12)
plt.ylabel('數(shù)量', fontsize=12)
plt.xticks(rotation=45, fontsize=10)
# 顯示圖表
plt.show()
3.5?盒圖 - 房屋價(jià)格分布
plt.figure(figsize=(10, 6))
sns.boxenplot(data=df, y='價(jià)格', color='purple')
plt.title('房屋價(jià)格分布', fontsize=16)
plt.ylabel('價(jià)格', fontsize=12)
plt.show()
3.6?條形圖 - 不同城市的房屋價(jià)格對(duì)比
plt.figure(figsize=(12, 6))
sns.barplot(data=df, x='城市', y='價(jià)格', palette='coolwarm')
plt.title('不同城市的房屋價(jià)格對(duì)比', fontsize=16)
plt.xlabel('城市', fontsize=12)
plt.ylabel('價(jià)格', fontsize=12)
plt.xticks(rotation=45, fontsize=10)
plt.show()
3.7 不同布局類型的房屋數(shù)量比較
# 計(jì)算每種布局類型的數(shù)量
layout_counts = df['布局'].value_counts().sort_values(ascending=True)[-10:]
# 設(shè)置水平條形圖
plt.figure(figsize=(10, 8))
colors = ['#66b3ff'] * len(layout_counts) # 使用單一顏色
plt.barh(layout_counts.index, layout_counts, color=colors)
# 添加標(biāo)題和軸標(biāo)簽
plt.title('不同布局類型的房屋數(shù)量比較', fontsize=16)
plt.xlabel('數(shù)量', fontsize=12)
plt.ylabel('布局類型', fontsize=12)
# 調(diào)整刻度標(biāo)簽的字體大小
plt.xticks(fontsize=10)
plt.yticks(fontsize=10)
# 顯示圖表
plt.show()
?
3.8 面積與價(jià)格的關(guān)系圖文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-771404.html
# 提取面積和價(jià)格的數(shù)據(jù)
area = df['面積']
price = df['價(jià)格']
# 設(shè)置散點(diǎn)圖
plt.figure(figsize=(10, 6))
plt.scatter(area, price, alpha=0.6, color='b', edgecolors='k')
# 添加標(biāo)題和軸標(biāo)簽
plt.title('面積與價(jià)格的關(guān)系圖', fontsize=16)
plt.xlabel('面積', fontsize=12)
plt.ylabel('價(jià)格', fontsize=12)
# 顯示圖表
plt.show()
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-771404.html
到了這里,關(guān)于python 房天下網(wǎng)站房?jī)r(jià)數(shù)據(jù)爬取與可視化分析的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!