爬虫---095scrapy_当当网数据爬取

目的:当当网(青春爱情文学类)爬取实现yield方法,管道封装,多条管道下                 载,多页数据下载

1.自定义文件 dang.py

import scrapy
from scrapy_095_ddw.items import Scrapy095DdwItem


class DangSpider(scrapy.Spider):
    name = "dang"
    #多页下载  allowed_domains一般情况下只写域名

    allowed_domains = ["category.dangdang.com"]
    start_urls = ["http://category.dangdang.com/cp01.01.02.00.00.00.html"]

    base_url = 'http://category.dangdang.com/pg'
    page = 1
    def parse(self, response):
        #pipelines  下载数据
        #items   定义数据结构

        #src = //ul[@class="bigimg"]/li//img/@src  图片反爬懒加载
        #src = //ul[@class="bigimg"]/li//img/@data-original
        #alt = //ul[@class="bigimg"]/li//img/@alt
        #price = //ul[@class="bigimg"]/li//p[@class="price"]/span[1]/text()
        #所有的seletor的对象  都可以再次调用xpath方法
        li_list = response.xpath('//ul[@class="bigimg"]/li')

        for li in li_list:
            src = li.xpath('.//img/@data-original').extract_first()
            #第一张图片的src与后面的不同,可以使用 其他的为data-original
            if src:
                src = src
            else:
                src = li.xpath('.//img/@src').extract_first()
            name = li.xpath('.//img/@alt').extract_first()
            price = li.xpath('.//p[@class="price"]/span[1]/text()').extract_first()


            book = Scrapy095DdwItem(src=src,name=name,price=price)

            #获取一个book就将book交给pipelines
            yield book

        #每一页爬取的业务逻辑一样,故只需要将执行的那个页的请求再次调用parse方法即可
        #http://category.dangdang.com/pg2-cp01.01.02.00.00.00.html
        #http://category.dangdang.com/pg3-cp01.01.02.00.00.00.html

        if self.page < 100:
            self.page = self.page + 1

            url = self.base_url + str(self.page) + '-cp01.01.02.00.00.00.html'

            #如何调用parse
            #scrapy.Request为scrapy的get请求
            #url为请求地址
            #callback为要执行的函数
            yield scrapy.Request(url=url,callback=self.parse)

2 管道 pipelines.py

import scrapy
from scrapy_095_ddw.items import Scrapy095DdwItem


class DangSpider(scrapy.Spider):
    name = "dang"
    #多页下载  allowed_domains一般情况下只写域名

    allowed_domains = ["category.dangdang.com"]
    start_urls = ["http://category.dangdang.com/cp01.01.02.00.00.00.html"]

    base_url = 'http://category.dangdang.com/pg'
    page = 1
    def parse(self, response):
        #pipelines  下载数据
        #items   定义数据结构

        #src = //ul[@class="bigimg"]/li//img/@src  图片反爬懒加载
        #src = //ul[@class="bigimg"]/li//img/@data-original
        #alt = //ul[@class="bigimg"]/li//img/@alt
        #price = //ul[@class="bigimg"]/li//p[@class="price"]/span[1]/text()
        #所有的seletor的对象  都可以再次调用xpath方法
        li_list = response.xpath('//ul[@class="bigimg"]/li')

        for li in li_list:
            src = li.xpath('.//img/@data-original').extract_first()
            #第一张图片的src与后面的不同,可以使用 其他的为data-original
            if src:
                src = src
            else:
                src = li.xpath('.//img/@src').extract_first()
            name = li.xpath('.//img/@alt').extract_first()
            price = li.xpath('.//p[@class="price"]/span[1]/text()').extract_first()


            book = Scrapy095DdwItem(src=src,name=name,price=price)

            #获取一个book就将book交给pipelines
            yield book

        #每一页爬取的业务逻辑一样,故只需要将执行的那个页的请求再次调用parse方法即可
        #http://category.dangdang.com/pg2-cp01.01.02.00.00.00.html
        #http://category.dangdang.com/pg3-cp01.01.02.00.00.00.html

        if self.page < 100:
            self.page = self.page + 1

            url = self.base_url + str(self.page) + '-cp01.01.02.00.00.00.html'

            #如何调用parse
            #scrapy.Request为scrapy的get请求
            #url为请求地址
            #callback为要执行的函数
            yield scrapy.Request(url=url,callback=self.parse)

3 items.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class Scrapy095DdwItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    #通俗而言  即为下载的数据

    #图片
    src = scrapy.Field()
    #名称
    name = scrapy.Field()
    #价格
    price = scrapy.Field()



    pass

4   settings

# Scrapy settings for scrapy_095_ddw 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.html

BOT_NAME = "scrapy_095_ddw"

SPIDER_MODULES = ["scrapy_095_ddw.spiders"]
NEWSPIDER_MODULE = "scrapy_095_ddw.spiders"


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "scrapy_095_ddw (+http://www.yourdomain.com)"

# 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 = {
#    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
#    "Accept-Language": "en",
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    "scrapy_095_ddw.middlewares.Scrapy095DdwSpiderMiddleware": 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    "scrapy_095_ddw.middlewares.Scrapy095DdwDownloaderMiddleware": 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




#管道可以有很多个  那么管道是有优先值的  优先值的范围是1到1000  值越小优先级越高
ITEM_PIPELINES = {
   "scrapy_095_ddw.pipelines.Scrapy095DdwPipeline": 300,

   "scrapy_095_ddw.pipelines.dangdangloadPipeline": 301,
}









# 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
#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 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"

# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"

【注】使用urllib.request.urlretrieve下载图片时,先在spiders目录下创建一个文件夹books用以存储图片



框架示意:

运行结果部分截图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值