需求:爬取【安居客—广州—新楼盘】的数据,具体到每个楼盘的详情页的若干字段。

难点:楼盘类型各式各样:住宅 别墅 商住 商铺 写字楼,不同楼盘字段的名称不一样。然后同一种类型,比如住宅,又分为不同的情况,比如分为期房在售,现房在售,待售,尾盘。其他类型也有类似情况。所以字段不能设置固定住。

解决方案:目前想到的解决方案,第一种:scrapy中items.py中不设置字段,spider中爬的时候自动识别字段(也就是有啥字段就保留下来),然后返回字典存起来。第二种,不同字段的网页分别写规则单独抓取。显然不可取。我采用的是第一种方案。还有其他方案的朋友们,欢迎交流哈。

目标网址为:http://gz.fang.anjuke.com/ 该网页下的楼盘数据

示例楼盘网址:http://gz.fang.anjuke.com/loupan/canshu-298205.html?from=loupan_tab

开始编写scrapy脚本。建立工程步骤略过。

1、count.py

 1 __author__ = 'Oscar_Yang'
 2 #-*- coding= utf-8 -*-
 3 """
 4     查看mongodb存储状况的脚本count.py
 5 """
 6 import time
 7 import pymongo
 8 client = pymongo.MongoClient("localhost", 27017)
 9 db = client["SCRAPY_anjuke_gz"]
10 sheet = db["anjuke_doc1"]
11
12 while True:
13     print(sheet.find().count())
14     print("____________________________________")
15     time.sleep(3)

1 """
2     entrypoint.py
3 """
4 from scrapy.cmdline import execute
5 execute(['scrapy', 'crawl', 'anjuke_gz'])

 1 # -*- coding: utf-8 -*-
 2 """
 3     settings.py
 4 """
 5
 6 # Scrapy settings for anjuke_gz project
 7 #
 8 # For simplicity, this file contains only settings considered important or
 9 # commonly used. You can find more settings consulting the documentation:
10 #
11 #     http://doc.scrapy.org/en/latest/topics/settings.html
12 #     http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
13 #     http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
14
15 BOT_NAME = 'anjuke_gz'
16
17 SPIDER_MODULES = ['anjuke_gz.spiders']
18 NEWSPIDER_MODULE = 'anjuke_gz.spiders'
19 MONGODB_HOST = "127.0.0.1"
20 MONGODB_PORT = 27017
21 MONGODB_DBNAME="SCRAPY_anjuke_gz"
22 MONGODB_DOCNAME="anjuke_doc1"
23
24 # Crawl responsibly by identifying yourself (and your website) on the user-agent
25 #USER_AGENT = 'anjuke_gz (+http://www.yourdomain.com)'
26
27 # Obey robots.txt rules
28 ROBOTSTXT_OBEY = False
29
30 # Configure maximum concurrent requests performed by Scrapy (default: 16)
31 #CONCURRENT_REQUESTS = 32
32
33 # Configure a delay for requests for the same website (default: 0)
34 # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
35 # See also autothrottle settings and docs
36 #DOWNLOAD_DELAY = 3
37 # The download delay setting will honor only one of:
38 #CONCURRENT_REQUESTS_PER_DOMAIN = 16
39 #CONCURRENT_REQUESTS_PER_IP = 16
40
41 # Disable cookies (enabled by default)
42 #COOKIES_ENABLED = False
43
44 # Disable Telnet Console (enabled by default)
45 #TELNETCONSOLE_ENABLED = False
46
47 # Override the default request headers:
48 #DEFAULT_REQUEST_HEADERS = {49 #   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
50 #   'Accept-Language': 'en',
51 #}
52
53 # Enable or disable spider middlewares
54 # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
55 #SPIDER_MIDDLEWARES = {56 #    'anjuke_gz.middlewares.AnjukeGzSpiderMiddleware': 543,
57 #}
58
59 # Enable or disable downloader middlewares
60 # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
61 #DOWNLOADER_MIDDLEWARES = {62 #    'anjuke_gz.middlewares.MyCustomDownloaderMiddleware': 543,
63 #}
64
65 # Enable or disable extensions
66 # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
67 #EXTENSIONS = {68 #    'scrapy.extensions.telnet.TelnetConsole': None,
69 #}
70
71 # Configure item pipelines
72 # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
73 ITEM_PIPELINES = {
74    'anjuke_gz.pipelines.AnjukeGzPipeline': 300,
75 }
76
77 # Enable and configure the AutoThrottle extension (disabled by default)
78 # See http://doc.scrapy.org/en/latest/topics/autothrottle.html
79 #AUTOTHROTTLE_ENABLED = True
80 # The initial download delay
81 #AUTOTHROTTLE_START_DELAY = 5
82 # The maximum download delay to be set in case of high latencies
83 #AUTOTHROTTLE_MAX_DELAY = 60
84 # The average number of requests Scrapy should be sending in parallel to
85 # each remote server
86 #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
87 # Enable showing throttling stats for every response received:
88 #AUTOTHROTTLE_DEBUG = False
89
90 # Enable and configure HTTP caching (disabled by default)
91 # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
92 HTTPCACHE_ENABLED = True
93 HTTPCACHE_EXPIRATION_SECS = 0
94 HTTPCACHE_DIR = 'httpcache'
95 HTTPCACHE_IGNORE_HTTP_CODES = []
96 HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

接下来,是items。因为没有设置字段,为默认的代码。

 1 # -*- coding: utf-8 -*-
 2
 3 # Define here the models for your scraped items
 4 #
 5 # See documentation in:
 6 # http://doc.scrapy.org/en/latest/topics/items.html
 7
 8 import scrapy
 9
10
11 class AnjukeGzItem(scrapy.Item):
12     # define the fields for your item here like:
13     # name = scrapy.Field()
14     pass

接下来,是piplines.py。在中设置了mongodb的配置。

# -*- coding: utf-8 -*-# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.htmlimport pymongo
from scrapy.conf import settingsclass AnjukeGzPipeline(object):def __init__(self):host=settings["MONGODB_HOST"]port=settings["MONGODB_PORT"]dbname=settings["MONGODB_DBNAME"]client=pymongo.MongoClient(port=port,host=host)tdb = client[dbname]self.post=tdb[settings["MONGODB_DOCNAME"]]def process_item(self,item,spider):info = dict(item)self.post.insert(info)return item

最后,是最主要的spider.py

 1 from scrapy.http import Request
 2 import scrapy
 3 from bs4 import BeautifulSoup
 4 import re
 5 import requests
 6 """
 7     spider脚本
 8 """
 9 class Myspider(scrapy.Spider):
10     name = 'anjuke_gz'
11     allowed_domains = ['http://gz.fang.anjuke.com/loupan/']
12     start_urls = ["http://gz.fang.anjuke.com/loupan/all/p{}/".format(i) for i in range(39)]
13
14     def parse(self, response):
15         soup = BeautifulSoup(response.text,"lxml")
16         content=soup.find_all(class_="items-name") #返回每个楼盘的对应数据
17         for item in content:
18             code=item["href"].split("/")[-1][:6]
19             real_href="http://gz.fang.anjuke.com/loupan/canshu-{}.html?from=loupan_tab".format(code) #拼凑出楼盘详情页的url
20             res=requests.get(real_href)
21             soup = BeautifulSoup(res.text,"lxml")
22             a = re.findall(r'<div class="name">(.*?)</div>', str(soup))
23             b = soup.find_all(class_="des")
24             data = {}
25             for (i, j) in zip(range(len(b)), a):
26                 data[j] = b[i].text.strip().strip("\t")
27                 data["url"] = real_href
28             yield data

下面是存入mongodb的情况。

  因为针对不同的网页结构,爬取的规则是一个,所以爬取的时候就不能针对每个字段进行爬取,所以存到库里的数据如果要是分析的话还需要清洗。

在python中使用mongodb的查询语句,再配合使用pandas应该就很方便清洗了。

转载于:https://www.cnblogs.com/coskaka/p/6165520.html

【scrapy实践】_爬取安居客_广州_新楼盘数据相关推荐

  1. 使用scrapy框架从爬取安居客数据到分析

    一.爬取数据 使用scrapy,不多说,上码 1.spider import scrapyfrom lianjia.items import anjukeItemclass AnjukeSpider( ...

  2. python 安居客 爬虫_爬虫学习6:爬取安居客的VR房源信息

    公司的VR产品在推广前夕,需要做一个较详细的市场分析报告,我们可以从下面几个步骤来深入探讨: 1.需要展望整个VR的市场规模有多大,从而论证我们需要面对的市场分量, 2.在这个大市场下面,我们面对的细 ...

  3. Python开发爬虫之BeautifulSoup解析网页篇:爬取安居客网站上北京二手房数据

    目标:爬取安居客网站上前10页北京二手房的数据,包括二手房源的名称.价格.几室几厅.大小.建造年份.联系人.地址.标签等. 网址为:https://beijing.anjuke.com/sale/ B ...

  4. 爬虫爬取安居客二手房和新房信息,你是买新房还是二手的呢?

    本文主要讲解爬取安居客买房类别中的二手房和新房,将提取的信息存储在记事本中,也可以转存CSV格式或者MongoDB中. 网站HTML信息提取比较简单,没有什么特别的地方,作为爬虫入门可以让初学者快速了 ...

  5. python爬虫爬取安居客并进行简单数据分析

    此篇博客为普通方式爬取安居客租房数据一共提取出1200条,但是在进行大规模的数据爬取时,不建议使用这种方式,速度太慢是最大的诟病,在进行大规模爬取时,使用分布式爬虫是第一选择 爬取过程 一.指定爬取数 ...

  6. Python爬取安居客新房信息

    由于是刚开始学习Python爬虫,做个简单的爬虫,提供一个学习思路. 由于水平有限,正则表达式写的实在是抠脚,就直接上BeautifulSoup了. BeautifulSoup的学习参考http:// ...

  7. python爬取安居客网站上北京二手房数据

    目标:爬取安居客网站上前10页北京二手房的数据,包括二手房源的名称.价格.几室几厅.大小.建造年份.联系人.地址.标签等. 网址为:https://beijing.anjuke.com/sale/ B ...

  8. Python爬取安居客经纪人信息

    Python爬取安居客经纪人信息 Python2.7.15 今天我们来爬取安居客经纪人的信息.这次我们不再使用正则,我们使用beautifulsoup.不了解的可以先看一下这个文档,便于理解.http ...

  9. 爬取安居客租房信息,主要是获取电话号码

    爬取安居客租房信息,主要是获取电话号码 想要得到个人房源的电话只能在app上获取,而且获取的是虚拟号码,没什么作用.所以我们这次获取的是经纪人房源的电话号码,随便打开一个网页,可以看到. 他的电话号码 ...

最新文章

  1. Java黑皮书课后题第3章:**3.15(游戏:彩票)修改程序清单3-8,产生三位整数的彩票。程序提示用户输入一个三位整数,然后依照规则判定用户是否赢得奖金
  2. 解决子线程操作UI的方法
  3. 使用gethostname()函数和gethostbyname()函数获取主机相关信息
  4. Exposure Mask of Digital Cameras
  5. 克隆网站工具_4 种开源云安全工具
  6. gcc/g++ 参数总结
  7. 没有基础的人可以学python吗-今天就来告诉你,没有编程基础的人适不适合学python...
  8. 中国省市区json数据 三级联动
  9. 1. NET 6.0 前言
  10. 最新版校园招聘进大厂系列----------(3)字节篇 -----未完待续
  11. wifi状态下实现文件传输
  12. vue出现client:172 [WDS] Disconnected!
  13. MFC与Windows编程
  14. word骨灰级水平,赶紧留一份.
  15. 2345浏览器劫持主页解决办法
  16. 12个固态硬盘优化技巧,延长固态硬盘使用寿命
  17. 实现图的邻接矩阵和邻接表的存储
  18. 面试不问技术_告诉不问模式的重构
  19. C#上位机开发串口通信
  20. 人工智能课程笔记:自然语言处理与循环神经网络

热门文章

  1. Geomagic Wrap2017软件安装以及蓝屏解决
  2. 【推荐系统】DeepFM模型分析
  3. 计算机视觉实战--OpenCV进行红绿灯识别
  4. 离线部署 Cloudera Manager 5 和 CDH 5.12.1 及使用 CDH 部署 Hadoop 集群服务
  5. Python构造函数、成员函数,类变量、成员变量和局部变量
  6. C/C++获取当前系统时间的方法
  7. 2021新版pycharm的下载教程
  8. 讲清楚embedding到底在干什么
  9. Rust腐蚀申述教程Rust被办申述处理
  10. happens-before是什么?JMM最最核心的概念,看完你就懂了