北邮 python 爬虫爬取链家的新房数据进行数据处理

2023-10-18 20:10

本文主要是介绍北邮 python 爬虫爬取链家的新房数据进行数据处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

博主声明:用途仅供学习


items.py


import scrapyclass MyItem(scrapy.Item):# define the fields for your item here like:name = scrapy.Field()    # 名称place1 = scrapy.Field()   # 地理位置place2 = scrapy.Field()place3 = scrapy.Field()model = scrapy.Field()   # 房型aera = scrapy.Field()   # 面积totalprice = scrapy.Field()   # 总价UnitPrice = scrapy.Field()    # 单价unit = scrapy.Field()    # 价格单位

spider.py

import scrapy
from linajia.items import MyItem  # 从items.py中引入MyItem对象class mySpider(scrapy.spiders.Spider):name = "linajia"  # 爬虫的名字是linajiaallowed_domains = ["bj.lianjia.com/"]  # 允许爬取的网站域名start_urls = ["https://bj.fang.lianjia.com/loupan/"]# 多页爬取for pg in range(2, 20):start_urls.append("https://bj.fang.lianjia.com/loupan/pg{}/".format(pg))# 减慢爬虫速度,保证顺序不乱序download_delay = 1def parse(self, response):  # 解析爬取的内容item = MyItem()  # 生成一个在items.py中定义好的Myitem对象,用于接收爬取的数据for each in response.xpath('/html/body/div[4]/ul[2]/li'):try:item['name'] = each.xpath("div/div[1]/a/text()").extract()[0]item['place1'] = each.xpath("div/div[2]/span[1]/text()").extract()[0]item['place2'] = each.xpath("div/div[2]/span[2]/text()").extract()[0]item['place3'] = each.xpath("div/div[2]/a/text()").extract()[0]#  取最小户型l = each.xpath("div/a/span[1]/text()").extract()if len(l) == 0:  # 最小户型的数据可能不存在,进行判断,如果不存在,那么赋值为''item['model'] = ''else:item['model'] = l[0]# item['aera']取最小面积l1 = each.xpath("div/div[3]/span/text()").extract()if len(l1):   # 最小面积的数据存在时,进行提取最小值str = l1[0]startpos = str.find(" ") + 1endpos = str.find("-")if endpos == -1:endpos = str.find("m")item['aera'] = str[startpos: endpos]else:   # 最小面积不存在时,赋值为空串''item['aera'] = ''# item['totalprice']l2 = each.xpath("div/div[6]/div[2]/text()").extract()# item['UnitPrice']l3 = each.xpath("div/div[6]/div[1]/span[1]/text()").extract()unit = each.xpath("div/div[6]/div/span[2]/text()").extract()# 由于存在网页显示均值的位置可能出现总价,那么进行如果进行不处理读取,会导致某些行的数据# 在均值的位置显示总价,而总价的位置显示为空if -1 != unit[0].find("总价"):item['totalprice'] = l3[0]   # 将均值处显示的总价放置于总价的位置item['UnitPrice'] = ''else:if len(l3) == 0:item['UnitPrice'] = ''else:item['UnitPrice'] = l3[0]if len(l2) == 0:item['totalprice'] = ''else:item['totalprice'] = l2[0]yield itemexcept ValueError:pass

DataProcess.py

import numpy as np
import pandas as pd# 打开CSV文件
fileNameStr = 'MyData.csv'
orig_df = pd.read_csv(fileNameStr, encoding='gbk', dtype=str)# 1.将字符串的列前后空格去掉
orig_df['name'] = orig_df['name'].str.strip()
orig_df['place1'] = orig_df['place1'].str.strip()
orig_df['place2'] = orig_df['place2'].str.strip()
orig_df['place3'] = orig_df['place3'].str.strip()
orig_df['model'] = orig_df['model'].str.strip()
orig_df['aera'] = orig_df['aera'].str.strip()
orig_df['totalprice'] = orig_df['totalprice'].str.strip()
orig_df['UnitPrice'] = orig_df['UnitPrice'].str.strip()# 2.将aera变为整型
orig_df['aera'] = orig_df['aera'].fillna(0).astype(np.int)# 3.将单价变为整型
orig_df['UnitPrice'] = orig_df['UnitPrice'].fillna(0).astype(np.int)# 3.价格处理
orig_df['totalprice'] = orig_df['totalprice'].str.replace("总价", "")
orig_df['totalprice'] = orig_df['totalprice'].str.replace("万/套", "")
orig_df['totalprice'] = orig_df['totalprice'].fillna(0).astype(np.int)# 4.总价计算
for idx, row in orig_df.iterrows():if orig_df.loc[idx, 'totalprice'] == 0:orig_df.loc[idx, 'totalprice'] = (orig_df.loc[idx, 'aera'] * orig_df.loc[idx, 'UnitPrice']) // 10000if orig_df.loc[idx, 'UnitPrice'] != 0:orig_df.loc[idx, 'UnitPrice'] = '%.4f' % (orig_df.loc[idx, 'UnitPrice'] / 10000)elif orig_df.loc[idx, 'UnitPrice'] == 0:orig_df.loc[idx, 'UnitPrice'] = '%.4f' % (orig_df.loc[idx, 'totalprice'] / orig_df.loc[idx, 'aera'])# 将填补的aera为空处复原# 5.面积复原,将填充的0去掉
orig_df['aera'] = orig_df['aera'].astype(np.str)
for idx, row in orig_df.iterrows():if orig_df.loc[idx, 'aera'] == '0':orig_df.loc[idx, 'aera'] = ''# 6.总价
# 最大值
print("总价:")
imaxpos = orig_df['totalprice'].idxmax()
print("最贵房屋", orig_df.loc[imaxpos, "totalprice"], orig_df.loc[imaxpos, "name"])
# 最小值
iminpos = orig_df['totalprice'].idxmin()
print("最便宜房屋", orig_df.loc[iminpos, "totalprice"], orig_df.loc[iminpos, "name"])
# 中位数
print("中位数", orig_df['totalprice'].median())# 7.单价
# 最大值
print("单价:")
idmaxpos = orig_df['UnitPrice'].astype(float).idxmax()
print("最贵房屋", orig_df.loc[idmaxpos, "UnitPrice"], orig_df.loc[idmaxpos, "name"])
# 最小值
idminpos = orig_df['UnitPrice'].astype(float).idxmin()
print("最便宜房屋", orig_df.loc[idminpos, "UnitPrice"], orig_df.loc[idminpos, "name"])
# 中位数
print("中位数", orig_df['UnitPrice'].median())orig_df.to_csv("NewMydata.csv", header=True, encoding="gbk", mode='w+', index=False)

处理结果
在这里插入图片描述

这篇关于北邮 python 爬虫爬取链家的新房数据进行数据处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/234878

相关文章

VSCode配置Anaconda Python环境的实现

《VSCode配置AnacondaPython环境的实现》VisualStudioCode中可以使用Anaconda环境进行Python开发,本文主要介绍了VSCode配置AnacondaPytho... 目录前言一、安装 Visual Studio Code 和 Anaconda二、创建或激活 conda

pytorch+torchvision+python版本对应及环境安装

《pytorch+torchvision+python版本对应及环境安装》本文主要介绍了pytorch+torchvision+python版本对应及环境安装,安装过程中需要注意Numpy版本的降级,... 目录一、版本对应二、安装命令(pip)1. 版本2. 安装全过程3. 命令相关解释参考文章一、版本对

大数据spark3.5安装部署之local模式详解

《大数据spark3.5安装部署之local模式详解》本文介绍了如何在本地模式下安装和配置Spark,并展示了如何使用SparkShell进行基本的数据处理操作,同时,还介绍了如何通过Spark-su... 目录下载上传解压配置jdk解压配置环境变量启动查看交互操作命令行提交应用spark,一个数据处理框架

讯飞webapi语音识别接口调用示例代码(python)

《讯飞webapi语音识别接口调用示例代码(python)》:本文主要介绍如何使用Python3调用讯飞WebAPI语音识别接口,重点解决了在处理语音识别结果时判断是否为最后一帧的问题,通过运行代... 目录前言一、环境二、引入库三、代码实例四、运行结果五、总结前言基于python3 讯飞webAPI语音

基于Python开发PDF转PNG的可视化工具

《基于Python开发PDF转PNG的可视化工具》在数字文档处理领域,PDF到图像格式的转换是常见需求,本文介绍如何利用Python的PyMuPDF库和Tkinter框架开发一个带图形界面的PDF转P... 目录一、引言二、功能特性三、技术架构1. 技术栈组成2. 系统架构javascript设计3.效果图

通过ibd文件恢复MySql数据的操作方法

《通过ibd文件恢复MySql数据的操作方法》文章介绍通过.ibd文件恢复MySQL数据的过程,包括知道表结构和不知道表结构两种情况,对于知道表结构的情况,可以直接将.ibd文件复制到新的数据库目录并... 目录第一种情况:知道表结构第二种情况:不知道表结构总结今天干了一件大事,安装1Panel导致原来服务

Nginx如何进行流量按比例转发

《Nginx如何进行流量按比例转发》Nginx可以借助split_clients指令或通过weight参数以及Lua脚本实现流量按比例转发,下面小编就为大家介绍一下两种方式具体的操作步骤吧... 目录方式一:借助split_clients指令1. 配置split_clients2. 配置后端服务器组3. 配

Python如何在Word中生成多种不同类型的图表

《Python如何在Word中生成多种不同类型的图表》Word文档中插入图表不仅能直观呈现数据,还能提升文档的可读性和专业性,本文将介绍如何使用Python在Word文档中创建和自定义各种图表,需要的... 目录在Word中创建柱形图在Word中创建条形图在Word中创建折线图在Word中创建饼图在Word

Python Excel实现自动添加编号

《PythonExcel实现自动添加编号》这篇文章主要为大家详细介绍了如何使用Python在Excel中实现自动添加编号效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、背景介绍2、库的安装3、核心代码4、完整代码1、背景介绍简单的说,就是在Excel中有一列h=会有重复

Jmeter如何向数据库批量插入数据

《Jmeter如何向数据库批量插入数据》:本文主要介绍Jmeter如何向数据库批量插入数据方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Jmeter向数据库批量插入数据Jmeter向mysql数据库中插入数据的入门操作接下来做一下各个元件的配置总结Jmete