一个小时多点,完成scrapy爬取官方网站新房的数据

2020-05-04 15:00:44 浏览数 (1)

前言

在前几天,接到一个大学生的作业的爬虫单子,要求采用scrapy爬取链家官方网站新房的数据(3-5页即可,太多可能被封禁ip),网址:https://bj.fang.lianjia.com/loupan/,将楼盘名称、价格、平米数等(可以拓展)数据保存到一个json文件中。

为了50块钱,废话不说就是开干。虽说我不是计算机的,还是一个屌丝大三化工学生。

分析网页

那么今天教大家用Scarpy爬取链家网,爬取网页如下:http://bj.fang.lianjia.com/loupan/。

点击其中的一个来看看,https://bj.fang.lianjia.com/loupan/p_zjtfbkrhf/?fb_expo_id=303816048586158080

新建项目

新建项目和爬虫文件这些太简单,都是老套路, pass了。新建的项目如下。

加请求头

第一步,傻逼都知道加请求头。

在setting.py加MY_USER_AGENT

代码语言:javascript复制
MY_USER_AGENT = [
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
    "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
    "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
    "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
    "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
    "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527  (KHTML, like Gecko, Safari/419.3) Arora/0.6",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
    "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
    "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
    "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
    "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
    "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
    "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
    "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
    "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
]

然后去Middleware.py去搞一个RandomUserAgentMiddleware,这代码找之前的scrapy爬虫项目直接复制,简单。

代码语言:javascript复制
import random
class RandomUserAgentMiddleware(object):
    def __init__(self, user_agents):
        self.user_agents = user_agents

    @classmethod
    def from_crawler(cls, crawler):
        # 从settings.py中导入MY_USER_AGENT
        s = cls(user_agents=crawler.settings.get('MY_USER_AGENT'))
        return s

    def process_request(self, request, spider):
        agent = random.choice(self.user_agents)
        request.headers['User-Agent'] = agent
        return None

去setting.py开启上它。900记得, 老套路。

代码语言:javascript复制
DOWNLOADER_MIDDLEWARES = {
   # 'lianjia.middlewares.LianjiaDownloaderMiddleware': 543,
   'lianjia.middlewares.RandomUserAgentMiddleware': 900,
}

OK,请求头headers搞定,代码都是复制的,3分钟OK。

搞定item

item就是把爬取的信息储存起来,爬取楼盘名称、类型,位置,价格、平米数,代码编写需要两分钟。

代码语言:javascript复制
import scrapy
'''
目标:爬取链家官方网站新房的数据(3-5页即可,太多可能被封禁ip)
网址:https://bj.fang.lianjia.com/loupan/
要求:将楼盘名称、价格、平米数等(可以拓展)数据保存到一个json文件中。
交付:整个project的压缩包
'''

class LianjiaItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()

    """楼盘名称、类型,位置,价格、平米数"""
    name = scrapy.Field()
    type = scrapy.Field()
    location = scrapy.Field()
    price = scrapy.Field()
    number = scrapy.Field()

首页调试

我们需要把详情页的url和建面面积匹配出来,scrapy shell https://bj.fang.lianjia.com/loupan进入shell调试。

在url的a标签发现了class = “resblock-name”的div,下面就是小儿科的东西。

没有域名,直接follow快捷方式完事,可以自动拼接url。

建面面积一样,轻松解决。

在span标签发现了class = “resblock-area”的div,重复下面的操作。

详情页调试

下面就是详情页了,scrapy shell https://bj.fang.lianjia.com/loupan/p_zjtfbkrhf/?fb_expo_id=303816048586158080

下面把楼盘名称搞出来,慢慢调试。

楼盘类型,位置,价格这些,我不一一找了。就是耐心的通过scrapy shell 调试。这里花费了有半个小时。

最后,自己看代码。

代码语言:javascript复制
import scrapy
from ..items import LianjiaItem

class SpiderSpider(scrapy.Spider):
    name = 'spider'
    allowed_domains = ['bj.fang.lianjia.com']
    start_urls = ['http://bj.fang.lianjia.com/loupan/']


    def parse(self, response):
        for i in range(1,22):
            page_url = 'https://bj.fang.lianjia.com/loupan/pg{}'.format(i)
            yield response.follow(page_url,callback =self.parse_page)

    def parse_page(self,response):
        urls = response.xpath("//div[@class='resblock-name']/a/@href").extract()
        nums = response.xpath("//div[@class='resblock-area']/span/text()").extract()
        print(urls)
        print(nums)
        for num,url in zip(nums,urls):
            # 用的follow快捷方式,可以自动拼接url
            yield response.follow(url=url, meta={'num':num},callback=self.parse_detail)
    def parse_detail(self,response):

        item = LianjiaItem()
        item['name'] = response.xpath("//div[@class='title-wrap']//h2/text()").extract_first()
        self.logger.info('正在爬取{}……'.format(item['name']))
        item['type'] = response.xpath("//div[@class='tags-wrap']/span[@class='tag-item house-type-tag']/text()").extract_first()
        item['location'] = response.xpath("//ul[@class='info-list']//span[@class='content']/text()").extract_first()
        item['price'] = response.xpath("//div[@class='price']/span[@class='price-number']/text()").extract_first()
        item['number'] = response.meta['num']
        yield item

保存json

要求保存json,直接 -o 省事,连Pipeline都不用写。

在setting中开启Pipeline。

代码语言:javascript复制
ITEM_PIPELINES = {
   'lianjia.pipelines.LianjiaPipeline': 300,
}

运行,开一个main.py,scrapy crawl spider -o spider.json

代码语言:javascript复制
'''
@Author:Runsen
@微信公众号:润森笔记
@博客:https://blog.csdn.net/weixin_44510615
@Date:2020/4/13
'''

import sys
import os
from scrapy.cmdline import execute
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute(['scrapy','crawl','spider','-o spider.json'])

运行时发现没有中文,看了下我scrapy博客https://maoli.blog.csdn.net/article/details/89012106,加上setting配置FEED_EXPORT_ENCODING = 'utf-8'完成。

代码语言:javascript复制
FEED_EXPORT_ENCODING = 'utf-8'

运行,ok

0 人点赞