需求:爬取【安居客—广州—新楼盘】的数据,具体到每个楼盘的详情页的若干字段。
难点:楼盘类型各式各样:住宅 别墅 商住 商铺 写字楼,不同楼盘字段的名称不一样。然后同一种类型,比如住宅,又分为不同的情况,比如分为期房在售,现房在售,待售,尾盘。其他类型也有类似情况。所以字段不能设置固定住。
解决方案:目前想到的解决方案,第一种: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
__author__ = 'Oscar_Yang'
#-*- coding= utf-8 -*-
"""
查看mongodb存储状况的脚本count.py
"""
import time
import pymongo
client = pymongo.MongoClient("localhost", 27017)
db = client["SCRAPY_anjuke_gz"]
sheet = db["anjuke_doc1"] while True:
print(sheet.find().count())
print("____________________________________")
time.sleep(3)
"""
entrypoint.py
"""
from scrapy.cmdline import execute
execute(['scrapy', 'crawl', 'anjuke_gz'])
# -*- coding: utf-8 -*-
"""
settings.py
""" # Scrapy settings for anjuke_gz project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'anjuke_gz' SPIDER_MODULES = ['anjuke_gz.spiders']
NEWSPIDER_MODULE = 'anjuke_gz.spiders'
MONGODB_HOST = "127.0.0.1"
MONGODB_PORT = 27017
MONGODB_DBNAME="SCRAPY_anjuke_gz"
MONGODB_DOCNAME="anjuke_doc1" # Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'anjuke_gz (+http://www.yourdomain.com)' # Obey robots.txt rules
ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.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 = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#} # Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'anjuke_gz.middlewares.AnjukeGzSpiderMiddleware': 543,
#} # Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'anjuke_gz.middlewares.MyCustomDownloaderMiddleware': 543,
#} # Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#} # Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'anjuke_gz.pipelines.AnjukeGzPipeline': 300,
} # Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_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 http://scrapy.readthedocs.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'
接下来,是items。因为没有设置字段,为默认的代码。
# -*- coding: utf-8 -*- # Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html import scrapy class AnjukeGzItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
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.html import pymongo
from scrapy.conf import settings class 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
from scrapy.http import Request
import scrapy
from bs4 import BeautifulSoup
import re
import requests
"""
spider脚本
"""
class Myspider(scrapy.Spider):
name = 'anjuke_gz'
allowed_domains = ['http://gz.fang.anjuke.com/loupan/']
start_urls = ["http://gz.fang.anjuke.com/loupan/all/p{}/".format(i) for i in range(39)] def parse(self, response):
soup = BeautifulSoup(response.text,"lxml")
content=soup.find_all(class_="items-name") #返回每个楼盘的对应数据
for item in content:
code=item["href"].split("/")[-1][:6]
real_href="http://gz.fang.anjuke.com/loupan/canshu-{}.html?from=loupan_tab".format(code) #拼凑出楼盘详情页的url
res=requests.get(real_href)
soup = BeautifulSoup(res.text,"lxml")
a = re.findall(r'<div class="name">(.*?)</div>', str(soup))
b = soup.find_all(class_="des")
data = {}
for (i, j) in zip(range(len(b)), a):
data[j] = b[i].text.strip().strip("\t")
data["url"] = real_href
yield data
下面是存入mongodb的情况。
因为针对不同的网页结构,爬取的规则是一个,所以爬取的时候就不能针对每个字段进行爬取,所以存到库里的数据如果要是分析的话还需要清洗。
在python中使用mongodb的查询语句,再配合使用pandas应该就很方便清洗了。