最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

settings.py豆瓣top电影数据爬取至mongoDB数据库

XAMPP案例 admin 758浏览 0评论

梦里不知身是客,一晌贪欢

通过scrapy框架将豆瓣top250电影信息数据进行爬取至数据库

1.settings.py:爬虫配置信息

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

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

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

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'crawlerprc01 (+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 = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}

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

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

# mongodb
host = '127.0.0.1'
port = 27017
db = 'my_test'
collection = 'web'

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

2.spiders.py:爬虫部分

# -*- coding: utf-8 -*-
import scrapy
from crawlerprc01.items import DoubanmovieItem

class DoubanmovieSpider(scrapy.Spider):
    name = 'doubanmovie'
    allowed_domains = ['movie.douban.com']
    start_urls = ['https://movie.douban.com/top250?start=0']
    base_domin = "https://movie.douban.com/top250"  # 每页的公共访问

    page = 1
    def parse(self, response):
        movies_info = response.xpath("//ol[@class='grid_view']/li")
        for movie_info in movies_info:
            movie_name = movie_info.xpath(".//div[@class='hd']//span[@class='title'][1]/text()").get()
            movie_sysnopsis = movie_info.xpath(".//div[@class='bd']/p/text()").getall()
            movie_score = movie_info.xpath(".//div[@class='star']//span[@class='rating_num']/text()").get()
            type = '豆瓣top电影'
            item = DoubanmovieItem(movie_name=movie_name, movie_sysnopsis=movie_sysnopsis, movie_score=movie_score, type=type)
            yield item
        self.page += 1
        next_url = response.xpath("//div[@class='paginator']/span[@class='next']/a/@href").get()
        if not next_url:
            print(f'豆瓣top电影爬取完毕,共{self.page-1}页')
        else:
            yield scrapy.Request(self.base_domin + next_url, callback=self.parse)

3.items.py:要爬取的数据模型

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

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

import scrapy

class DoubanmovieItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    movie_name = scrapy.Field()
    movie_sysnopsis = scrapy.Field()
    movie_score = scrapy.Field()
    type = scrapy.Field()

4.pipelines:数据获取

# -*- 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 pymongo import MongoClient  # mongodb
from crawlerprc01 import settings  # 便于数据库传参

# 糗事百科
class DoubanmovieSpider(object):
    def open_spider(self, spider):
        print("开始爬取豆瓣top电影...")

    def __init__(self):
        # 链接数据库
        self.client = MongoClient(host=settings.host, port=settings.port)
        # 连接数据库
        self.db = self.client[settings.db]
        # 连接集合
        self.collection = self.db[settings.collection]

    def process_item(self, item, spider):
        data = dict(item)
        # 向指定的集合里添加数据
        self.collection.insert(data)
        return item

    def colse_spider(self, spideer):
        print("豆瓣top电影爬取结束...")

转载请注明:XAMPP中文组官网 » settings.py豆瓣top电影数据爬取至mongoDB数据库

您必须 登录 才能发表评论!