链接:https://jn.zu.ke.com/zufang
首先我们使用scrapy startproject Beike 这个命令创建一个scrapy爬虫项目,接着我们用pycharm打开项目,完善item

接着我们找到setting文件,把ROBOTSTXT_OBEY = True,注释掉,或删除,表示我们不遵守协议

设置请求头,伪装成浏览器,不设置直接识别scrapy爬虫框架,直接把你机器拉入黑名单

我们抓取的是页面上的信息字段
我们明确了item以后,我们开始一个scrapy爬虫项目,使用命令: scrapy genspider beike jn.zu.ke.com

beike ------ 是爬虫名字
beike jn.zu.ke.com – domain

接下来我们先编写爬虫文件先写解析列表页面,还有详情页面,我们先不进行翻页,一步一步实现:

代码如下:

# -*- coding: utf-8 -*-
import scrapy
from Beike.items import BeikeItem
import copyclass BeikeSpider(scrapy.Spider):name = 'beike'allowed_domains = ['jn.zu.ke.com']start_urls = ['https://jn.zu.ke.com/zufang']page = 2def parse(self, response):print(response.url)node_list = response.xpath('//div[@class="content__list--item--main"]')print(len(node_list))item = BeikeItem()for node in node_list:item["title"] = node.xpath("./p[1]/a/text()").extract_first().strip()item["link"] = response.urljoin(node.xpath("./p[1]/a/@href").extract_first().strip())item["address"] = node.xpath("./p[2]/a[3]/text()").extract_first().strip()item["big"] = node.xpath("./p[2]/text()[5]").extract_first().strip()item["where"] = node.xpath("./p[2]/text()[6]").extract_first().strip()item["how"] = node.xpath("./p[2]/text()[7]").extract_first().strip()item["price"] = node.xpath('./span[@class="content__list--item-price"]/em/text()').extract_first().strip() + '元/月'yield scrapy.Request(url=item["link"],callback=self.detail_parse,meta={"item": copy.deepcopy(item)},dont_filter=True)def detail_parse(self, response):item = response.meta['item']item["name"] = response.xpath('//*[@id="aside"]/div[2]/div[2]/div[1]/span/text()').extract_first()print(item["title"])yield item

因为翻页是动态加载的,我们就直接拼接下一页链接

第二页:https://jn.zu.ke.com/zufang/pg2/#contentList
第三页:https://jn.zu.ke.com/zufang/pg3/#contentList

发现变化的是pg后面的数字,构建代码:

        if self.page < 100:next_url = 'https://jn.zu.ke.com/zufang/pg{}/#contentList'.format(self.page)self.page += 1yield scrapy.Request(next_url, callback=self.parse)

交给scrapy框架进行请求解析,昨晚有一个bug一直困扰,就是解析列表页数据正常,但是解析详情页就出现了问题,最后打印数据是一样的,找了好久,然后通过百度找到了解决方法那就是导入copy模块,将列表的item传递使用深拷贝一下就好了meta={“item”: copy.deepcopy(item)},切记爬虫编写时,一定要注意对应好item字段,否则报错注意一定要打开dont_fillter,不过滤,不打开了就会出现一个bug,当前页面会referer到上一页,数据一样就像这样

我们写完spider爬虫后,运行爬虫 scrapy crawl beike 查看效果:

下一步我们我们将数据保存csv,使用pipline管道,将数据写入

注意:一定要在setting文件中注册管道后面数值越小,越优先

保存csv效果

全部代码:

爬虫item文件代码

# -*- coding: utf-8 -*-# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass BeikeItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()title = scrapy.Field()link = scrapy.Field()address = scrapy.Field()big = scrapy.Field()where = scrapy.Field()how = scrapy.Field()price = scrapy.Field()name = scrapy.Field()

spider爬虫文件:

# -*- coding: utf-8 -*-
import scrapy
from Beike.items import BeikeItem
import copyclass BeikeSpider(scrapy.Spider):name = 'beike'allowed_domains = ['jn.zu.ke.com']start_urls = ['https://jn.zu.ke.com/zufang']page = 2def parse(self, response):print(response.url)node_list = response.xpath('//div[@class="content__list--item--main"]')print(len(node_list))item = BeikeItem()for node in node_list:item["title"] = node.xpath("./p[1]/a/text()").extract_first().strip()item["link"] = response.urljoin(node.xpath("./p[1]/a/@href").extract_first().strip())item["address"] = node.xpath("./p[2]/a[3]/text()").extract_first().strip()item["big"] = node.xpath("./p[2]/text()[5]").extract_first().strip()item["where"] = node.xpath("./p[2]/text()[6]").extract_first().strip()item["how"] = node.xpath("./p[2]/text()[7]").extract_first().strip()item["price"] = node.xpath('./span[@class="content__list--item-price"]/em/text()').extract_first().strip() + '元/月'yield scrapy.Request(url=item["link"],callback=self.detail_parse,meta={"item": copy.deepcopy(item)},dont_filter=True)if self.page < 100:next_url = 'https://jn.zu.ke.com/zufang/pg{}/#contentList'.format(self.page)self.page += 1yield scrapy.Request(next_url, callback=self.parse)def detail_parse(self, response):item = response.meta['item']item["name"] = response.xpath('//*[@id="aside"]/div[2]/div[2]/div[1]/span/text()').extract_first()print(item["title"])yield item

pipline代码

# -*- coding: utf-8 -*-# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import csvclass SavePipeline(object):def open_spider(self, spider):self.file = open("贝壳.csv", 'a', newline="",encoding="gb18030")self.csv_writer = csv.writer(self.file)self.csv_writer.writerow(["标题", "链接", '地址', "大小", "方向", "居室","价格", "名字"])def process_item(self, item, spider):self.csv_writer.writerow([item["title"], item["link"], item["address"],item["big"], item["where"], item["how"], item["price"], item["name"]])return itemdef close_spider(self, spider):self.file.close()

setting文件

# -*- coding: utf-8 -*-# Scrapy settings for Beike project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.htmlBOT_NAME = 'Beike'SPIDER_MODULES = ['Beike.spiders']
NEWSPIDER_MODULE = 'Beike.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 ' \'Safari/537.36 '# Obey robots.txt rules
# ROBOTSTXT_OBEY = True# Configure maximum concurrent requests performed by Scrapy (default: 16)
# CONCURRENT_REQUESTS = 32# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
# DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
# CONCURRENT_REQUESTS_PER_DOMAIN = 16
# CONCURRENT_REQUESTS_PER_IP = 16# Disable cookies (enabled by default)
# COOKIES_ENABLED = False# Disable Telnet Console (enabled by default)
# TELNETCONSOLE_ENABLED = False# Override the default request headers:
# DEFAULT_REQUEST_HEADERS = {#     "Referer": "https://jn.zu.ke.com/zufang"
# }# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
# SPIDER_MIDDLEWARES = {#    'Beike.middlewares.BeikeSpiderMiddleware': 543,
# }# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# DOWNLOADER_MIDDLEWARES = {#    'Beike.middlewares.BeikeDownloaderMiddleware': 543,
# }# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
# EXTENSIONS = {#    'scrapy.extensions.telnet.TelnetConsole': None,
# }# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {'Beike.pipelines.SavePipeline': 300,
}# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
# AUTOTHROTTLE_ENABLED = True
# The initial download delay
# AUTOTHROTTLCONCURRENT_REQUESTSE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
# AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
# AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
# AUTOTHROTTLE_DEBUG = False# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
# HTTPCACHE_ENABLED = True
# HTTPCACHE_EXPIRATION_SECS = 0
# HTTPCACHE_DIR = 'httpcache'
# HTTPCACHE_IGNORE_HTTP_CODES = []
# HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

整个代码实现比较简单,就是有坑,每个人主要就是从项目中积累经验吧,这个网站,没有反爬,也没cookie模拟登录,后续遇到反爬可以用一个请求头池,还有ip代理池,进行持续化抓取数据,以上都是个人学习经验,如有不正请指教,谢谢!

scrapy抓取贝壳找房租房数据相关推荐

  1. Python爬虫 | 爬取贝壳找房8万+二手房源,看看普通人在北京买房是有多难!

    文章目录 1.概述 2.数据采集 3.数据清洗 3.1.读取数据 3.2.去掉车位(地下室)数据 3.3.房源信息解析 4.数据处理及可视化 4.1.各地区二手房源数 4.2.各地区二手房均价 4.3 ...

  2. python爬取贝壳找房之北京二手房源信息

    所用库 requests xpath解析库 multiprocessing多进程 pandas库用于保存csv文件 实战背景 本文首发于:python爬取贝壳找房之北京二手房源信息 主要是为了做北京二 ...

  3. 贝壳找房二手房信息爬虫

    爬取贝壳找房二手房信息代码: 把前滩替换为任意想要查询的区域即可查询: 数据保存至当前文件夹csv文件中. // An highlighted block import requests from l ...

  4. 贝壳找房《2018城市居住报告》:新一线租房量持续攀升

    2019年1月24日,贝壳找房发布<2018城市居住报告>,聚焦租房和二手房交易人群,盘点分析了北京.上海.深圳.南京.武汉.长沙.重庆.成都.合肥等9大房产交易城市现状.报告发现,过去一 ...

  5. Python进阶之Scrapy抓取苏宁图书数据

    Python进阶之Scrapy抓取苏宁图书数据 1. 需求 2. 代码示例: 创建项目 start.py settings.py iterms.py snb.py pipelines.py 3. 注意 ...

  6. 数据吞吐量高达800亿条!实时计算在贝壳找房的应用实践

    摘要:本文由贝壳找房实时计算负责人刘力云分享,主要内容为 Apache Flink 在贝壳找房业务中的应用,分为以下三方面: 业务规模与演进 Hermes 实时计算平台介绍 未来发展与规划 重要:点击 ...

  7. 数据吞吐高达 21 亿条!实时计算在贝壳找房的应用实践

    摘要:本文由贝壳找房实时计算负责人刘力云分享,主要内容为 Apache Flink 在贝壳找房业务中的应用,分为以下三方面: 业务规模与演进 Hermes 实时计算平台介绍 未来发展与规划 重要:点击 ...

  8. 逆向爬虫18 Scrapy抓取全站数据和Redis入门

    逆向爬虫18 Scrapy抓取全站数据和Redis入门 一.全站数据抓取 1. 什么是抓取全站数据? 我们曾经在过猪八戒,图片之家,BOSS直聘等网站,利用网站官方提供的搜索功能,搜索指定关键词的内容 ...

  9. python—简单数据抓取七(采取蘑菇API代理设置scrapy的代理IP池并利用redis形成队列依次使用,利用ip池访问网页并将scrapy爬取转移到items的数据存入到数据库)

    学习目标: Python学习二十七-简单数据抓取七 学习内容: 1.采取蘑菇API代理设置scrapy的代理IP池并利用redis形成队列依次使用 2.利用ip池访问网页并将scrapy爬取转移到it ...

  10. 贝壳找房app使用Glide替换Picasso

    贝壳找房app使用Glide替换Picasso 现状 改造成本 原理 Glide比Picasso的2个优势: 展望 现状 操作步骤:打开贝壳找房,设置城市为"徐州", 然后点击&q ...

最新文章

  1. netsh命令修改ip
  2. 赠书 | 图像分类问题建模方案探索实践
  3. 还需要“attention”吗?一堆“前馈层”在ImageNet上表现得出奇得好
  4. Pycharm如何设置自定义背景颜色
  5. [转] SQL Server中变量的声明和使用方法
  6. 沉得住气的程序员们!
  7. 计算机网络校园网络设计方案,毕业论文--《计算机网络》校园网设计方案
  8. rm: cannot remove `.user.ini‘: Operation not permitted异常该如何解决?
  9. js 格式化输出_JS之 调试
  10. 集结六大行业领袖,「数据科学家」新课全球首发!
  11. 3dmax渲染出来的图不清晰?
  12. python基础篇:字符画生成~甜心教主
  13. Java 线程池及参数动态调节详解
  14. 英国内政部(Home Office)间谍机构(spy powers)假装它是Ofcom咨询中的一名私人公民1514378402983...
  15. 《Word2vec》1 模型的引入介绍与相关概念
  16. Ubuntu 16.04 下 旋转显示器屏幕 竖屏显示
  17. Android精品软件汇总(不断更新)
  18. DataBinding的使用一
  19. php 支付宝 当面付(个人账号免签约)
  20. 跨专业本科毕业小白程序员的入职心得——第一篇

热门文章

  1. 飞天云动港交所上市:市值39亿港元 成港股元宇宙第一股
  2. 大前端-阶段2 - 模块2 - 前端工程化实战-模块化开发(ESModule)-打包工具(webpack4)
  3. “博观而约取,厚积而薄发”——苏东坡
  4. 主成分分析逆变换_主成分分析方法操作
  5. [分析力学]解题思路 - 最小作用量原理
  6. 5-IP地址、端口、DNS服务器
  7. Oracle VM VirtualBox 安装增强功能
  8. html5 js实现ppt制作,impress.js前端制作酷炫ppt详细教程
  9. celery异步发送邮箱
  10. 用u盘进不了pe计算机意外地,u盘装系统启动不了无法进入pe怎么办