北邮 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

相关文章

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

MySQL 删除数据详解(最新整理)

《MySQL删除数据详解(最新整理)》:本文主要介绍MySQL删除数据的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、前言二、mysql 中的三种删除方式1.DELETE语句✅ 基本语法: 示例:2.TRUNCATE语句✅ 基本语

Python设置Cookie永不超时的详细指南

《Python设置Cookie永不超时的详细指南》Cookie是一种存储在用户浏览器中的小型数据片段,用于记录用户的登录状态、偏好设置等信息,下面小编就来和大家详细讲讲Python如何设置Cookie... 目录一、Cookie的作用与重要性二、Cookie过期的原因三、实现Cookie永不超时的方法(一)

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提