2018 - Python 3.7 爬虫之 利用 Scrapy 框架 抓取百度图片并保存(三)

版权声明:柠萌 https://blog.csdn.net/Hack_Different/article/details/83867543

一、编辑 items.py 文件

二、编辑 settings.py 文件

三、数据分析

四、创建爬虫文件 jmy.py

五、创建 main.py 文件,用于启动爬虫


一、编辑 items.py 文件

# -*- coding: utf-8 -*-

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

import scrapy
from scrapy import Field

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

二、编辑 settings.py 文件

# -*- coding: utf-8 -*-

# Scrapy settings for jmySpider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://doc.scrapy.org/en/latest/topics/settings.html
#     https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://doc.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'jmySpider'

SPIDER_MODULES = ['jmySpider.spiders']
NEWSPIDER_MODULE = 'jmySpider.spiders'

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

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# 修改编码为utf-8
# FEED_EXPORT_ENCODING = 'utf-8'

# 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://doc.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://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'jmySpider.middlewares.JmyspiderSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'jmySpider.middlewares.JmyspiderDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html

ITEM_PIPELINES = {
   'jmySpider.pipelines.JmyspiderPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://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 https://doc.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'

三、数据分析

注:可以跳过,进行第四步,先查看结果

测试链接:http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E9%87%91%E6%9C%A8%E7%A0%94

1. 分析链接

2. 获取数据链接

将上面的链接放入 jmy.py 文件的 start_urls 中即可

四、创建爬虫文件 jmy.py

# -*- coding: utf-8 -*-
from scrapy.spiders import CrawlSpider
from jmySpider.items import JmyspiderItem
import json

class JmySpider(CrawlSpider):

    name = 'jmySpider'

    # 设置headers伪装成浏览器
    headers = {
        'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'
    }

    # 主链接为 http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E9%87%91%E6%9C%A8%E7%A0%94
    # ajax 数据链接如下↓

    # 初始URL
    start_urls = [
        'http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E9%87%91%E6%9C%A8%E7%A0%94&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&word=%E9%87%91%E6%9C%A8%E7%A0%94&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=1&fr=&expermode=&pn=30&rn=30&gsm=1e&1541678883249=',
        'http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E9%87%91%E6%9C%A8%E7%A0%94&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&word=%E9%87%91%E6%9C%A8%E7%A0%94&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=1&fr=&expermode=&pn=60&rn=30&gsm=3c&1541678883388='
    ]

    def parse(self, response):
        # 从Json文件内容中提取所有img的内容
        imgs = json.loads(response.body)['data']
        for eachImage in imgs:
            item = JmyspiderItem()  # items中的类
            try:
                item['image_url'] = [eachImage['middleURL']]
                yield item
            except Exception as e:
                print(e)

五、创建 main.py 文件,用于启动爬虫

from scrapy import cmdline
cmdline.execute("scrapy crawl jmySpider -o result.csv".split())  #用命令行启动

运行 main.py 即可

展开阅读全文

没有更多推荐了,返回首页