scrapy爬虫框架-爬取多个网页

Posted 终不似

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scrapy爬虫框架-爬取多个网页相关的知识,希望对你有一定的参考价值。

scrapy爬虫框架(四)

爬取多个网页

思路:通过判断句子控网站中,下一页是否还有a标签来获取网址,拼接后继续爬取,最终写入json文件中。

技术图片

juziSpider.py

# -*- coding: utf-8 -*-
import scrapy

from juzi.items import JuziItem


class JuzispiderSpider(scrapy.Spider):
    name = 'juziSpider'
    allowed_domains = ['www.juzikong.com']
    start_urls = ['https://www.juzikong.com/tags/%E5%8F%A5%E5%AD%90%E8%BF%B7?page=1']
    base_domain = "https://www.juzikong.com"

    def parse(self, response):

        juzis = response.xpath('//div[@class="list_1fuFI"]//section')
        print (juzis)
        print("*" * 50)
        for juzi in juzis:
            content = juzi.xpath('.//a//span//span//span//text()').getall()
            author = juzi.xpath(".//div/span/span/span/span/text()").get()
            content="".join(content)#列表转化为字符串
            if not author:
                author="匿名"
            print(author,":",content)
            item = JuziItem(author=author,content=content)
            yield item
        print("*" * 50,)
        next_url = response.xpath("//button[@class='btn-next']//a/@href").get()
        if not next_url:
            return
        else:
            yield scrapy.Request(self.base_domain+next_url,callback=self.parse)

settings.py

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

# Scrapy settings for juzi 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 = 'juzi'

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


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'juzi (+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 https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 1
# 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',
#}
# 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',
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}

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

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'juzi.middlewares.JuziDownloaderMiddleware': 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
ITEM_PIPELINES = {
   'juzi.pipelines.JuziPipeline': 300,
}

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

pipelines.py

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

from scrapy.exporters import JsonLinesItemExporter

class JuziPipeline(object):
    def __init__(self):  # 初始化方法
        # 使用二进制来写入,因此“w”-->"wb"
        self.fp = open("juzi.json", "wb")
        self.exporter = JsonLinesItemExporter(self.fp, ensure_ascii=False, encoding='utf-8')
        # self.exporter.start_exporting()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

    def open_spider(self, spider):
        print("爬虫开始了!")

    def close_spider(self, spider):
        # self.exporter.finish_exporting()
        self.fp.close()
        print("爬虫结束了!")

以上是关于scrapy爬虫框架-爬取多个网页的主要内容,如果未能解决你的问题,请参考以下文章

python网络爬虫之使用scrapy自动爬取多个网页

scrapy主动退出爬虫的代码片段(python3)

Scrapy爬虫 爬取豆瓣TOP250

爬虫框架之Scrapy

爬虫框架Scrapy之Spider

python爬虫入门Scrapy框架之CrawlSpider类