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

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

批量导入txt数据到的redis过程

《批量导入txt数据到的redis过程》用户通过将Redis命令逐行写入txt文件,利用管道模式运行客户端,成功执行批量删除以Product*匹配的Key操作,提高了数据清理效率... 目录批量导入txt数据到Redisjs把redis命令按一条 一行写到txt中管道命令运行redis客户端成功了批量删除k

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Python标准库之数据压缩和存档的应用详解

《Python标准库之数据压缩和存档的应用详解》在数据处理与存储领域,压缩和存档是提升效率的关键技术,Python标准库提供了一套完整的工具链,下面小编就来和大家简单介绍一下吧... 目录一、核心模块架构与设计哲学二、关键模块深度解析1.tarfile:专业级归档工具2.zipfile:跨平台归档首选3.