diff --git a/desafioAmericanas/quotes_spider.py b/desafioAmericanas/quotes_spider.py new file mode 100644 index 0000000..fe4584c --- /dev/null +++ b/desafioAmericanas/quotes_spider.py @@ -0,0 +1,18 @@ +import scrapy + +class QuotesSpider(scrapy.Spider): + name = 'quotes' + + def start_requests(self): + urls = ['http://quotes.toscrape.com/page/1', 'http://quotes.toscrape.com/page/2'] + + for url in urls: + yield scrapy.Request(url=url, callback=self.parse) + + def parse(self, response): + pagina = response.url.split("/")[-2] + nome_arquivo = f'quotes-{page}.html' + with open(nome_arquivo, 'wb') as f: + f.write(response.body) + + self.log('Arquivo salvo {}'.format(nome_arquivo)) diff --git a/desafioAmericanas/raspagem/raspagem/__init__.py b/desafioAmericanas/raspagem/raspagem/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/desafioAmericanas/raspagem/raspagem/__pycache__/__init__.cpython-38.pyc b/desafioAmericanas/raspagem/raspagem/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000..69312ec Binary files /dev/null and b/desafioAmericanas/raspagem/raspagem/__pycache__/__init__.cpython-38.pyc differ diff --git a/desafioAmericanas/raspagem/raspagem/__pycache__/pipelines.cpython-38.pyc b/desafioAmericanas/raspagem/raspagem/__pycache__/pipelines.cpython-38.pyc new file mode 100644 index 0000000..e59987a Binary files /dev/null and b/desafioAmericanas/raspagem/raspagem/__pycache__/pipelines.cpython-38.pyc differ diff --git a/desafioAmericanas/raspagem/raspagem/__pycache__/settings.cpython-38.pyc b/desafioAmericanas/raspagem/raspagem/__pycache__/settings.cpython-38.pyc new file mode 100644 index 0000000..67b56df Binary files /dev/null and b/desafioAmericanas/raspagem/raspagem/__pycache__/settings.cpython-38.pyc differ diff --git a/desafioAmericanas/raspagem/raspagem/items.py b/desafioAmericanas/raspagem/raspagem/items.py new file mode 100644 index 0000000..e3e6706 --- /dev/null +++ b/desafioAmericanas/raspagem/raspagem/items.py @@ -0,0 +1,12 @@ +# Define here the models for your scraped items +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/items.html + +import scrapy + + +class RaspagemItem(scrapy.Item): + # define the fields for your item here like: + # name = scrapy.Field() + pass diff --git a/desafioAmericanas/raspagem/raspagem/middlewares.py b/desafioAmericanas/raspagem/raspagem/middlewares.py new file mode 100644 index 0000000..762c0c2 --- /dev/null +++ b/desafioAmericanas/raspagem/raspagem/middlewares.py @@ -0,0 +1,103 @@ +# Define here the models for your spider middleware +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/spider-middleware.html + +from scrapy import signals + +# useful for handling different item types with a single interface +from itemadapter import is_item, ItemAdapter + + +class RaspagemSpiderMiddleware: + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the spider middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_spider_input(self, response, spider): + # Called for each response that goes through the spider + # middleware and into the spider. + + # Should return None or raise an exception. + return None + + def process_spider_output(self, response, result, spider): + # Called with the results returned from the Spider, after + # it has processed the response. + + # Must return an iterable of Request, or item objects. + for i in result: + yield i + + def process_spider_exception(self, response, exception, spider): + # Called when a spider or process_spider_input() method + # (from other spider middleware) raises an exception. + + # Should return either None or an iterable of Request or item objects. + pass + + def process_start_requests(self, start_requests, spider): + # Called with the start requests of the spider, and works + # similarly to the process_spider_output() method, except + # that it doesn’t have a response associated. + + # Must return only requests (not items). + for r in start_requests: + yield r + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) + + +class RaspagemDownloaderMiddleware: + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the downloader middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_request(self, request, spider): + # Called for each request that goes through the downloader + # middleware. + + # Must either: + # - return None: continue processing this request + # - or return a Response object + # - or return a Request object + # - or raise IgnoreRequest: process_exception() methods of + # installed downloader middleware will be called + return None + + def process_response(self, request, response, spider): + # Called with the response returned from the downloader. + + # Must either; + # - return a Response object + # - return a Request object + # - or raise IgnoreRequest + return response + + def process_exception(self, request, exception, spider): + # Called when a download handler or a process_request() + # (from other downloader middleware) raises an exception. + + # Must either: + # - return None: continue processing this exception + # - return a Response object: stops process_exception() chain + # - return a Request object: stops process_exception() chain + pass + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) diff --git a/desafioAmericanas/raspagem/raspagem/pipelines.py b/desafioAmericanas/raspagem/raspagem/pipelines.py new file mode 100644 index 0000000..62990ac --- /dev/null +++ b/desafioAmericanas/raspagem/raspagem/pipelines.py @@ -0,0 +1,35 @@ +# 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 + + +# useful for handling different item types with a single interface +from itemadapter import ItemAdapter +import pymongo + +class RaspagemPipeline: + + collection_name = 'matheus_rodrigues' + + def __init__(self, mongo_uri, mongo_db): + self.mongo_uri = mongo_uri + self.mongo_db = mongo_db + + @classmethod + def from_crawler(cls, crawler): + return cls( + mongo_uri = crawler.settings.get('MONGO_URI'), + mongo_db = crawler.settings.get('MONGO_DATABASE', 'quotestoscrape') + ) + + def open_spider(self, spider): + self.client = pymongo.MongoClient(self.mongo_uri) + self.db = self.client[self.mongo_db] + + def close_spider(self, spider): + self.client.close() + + def process_item(self, item, spider): + self.db[self.collection_name].insert_one(ItemAdapter(item).asdict()) + return item diff --git a/desafioAmericanas/raspagem/raspagem/settings.py b/desafioAmericanas/raspagem/raspagem/settings.py new file mode 100644 index 0000000..8b6fb61 --- /dev/null +++ b/desafioAmericanas/raspagem/raspagem/settings.py @@ -0,0 +1,92 @@ +# Scrapy settings for raspagem 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 = 'raspagem' + +SPIDER_MODULES = ['raspagem.spiders'] +NEWSPIDER_MODULE = 'raspagem.spiders' + + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +#USER_AGENT = 'raspagem (+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 = { +# 'raspagem.middlewares.RaspagemSpiderMiddleware': 543, +#} + +# Enable or disable downloader middlewares +# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +#DOWNLOADER_MIDDLEWARES = { +# 'raspagem.middlewares.RaspagemDownloaderMiddleware': 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 = { + 'raspagem.pipelines.RaspagemPipeline': 300, +} + +MONGO_URI = 'mongodb+srv://desafioAmericanasUser:53GRppW17sxeeZkt@cluster0.gdf8e.mongodb.net/?retryWrites=true&w=majority' +MONGO_DATABASE = 'quotestoscrape' + + +# 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' diff --git a/desafioAmericanas/raspagem/raspagem/spiders/__init__.py b/desafioAmericanas/raspagem/raspagem/spiders/__init__.py new file mode 100644 index 0000000..ebd689a --- /dev/null +++ b/desafioAmericanas/raspagem/raspagem/spiders/__init__.py @@ -0,0 +1,4 @@ +# This package will contain the spiders of your Scrapy project +# +# Please refer to the documentation for information on how to create and manage +# your spiders. diff --git a/desafioAmericanas/raspagem/raspagem/spiders/__pycache__/__init__.cpython-38.pyc b/desafioAmericanas/raspagem/raspagem/spiders/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000..2d47085 Binary files /dev/null and b/desafioAmericanas/raspagem/raspagem/spiders/__pycache__/__init__.cpython-38.pyc differ diff --git a/desafioAmericanas/raspagem/raspagem/spiders/__pycache__/raspagem_spider.cpython-38.pyc b/desafioAmericanas/raspagem/raspagem/spiders/__pycache__/raspagem_spider.cpython-38.pyc new file mode 100644 index 0000000..8a3b1a2 Binary files /dev/null and b/desafioAmericanas/raspagem/raspagem/spiders/__pycache__/raspagem_spider.cpython-38.pyc differ diff --git a/desafioAmericanas/raspagem/raspagem/spiders/raspagem_spider.py b/desafioAmericanas/raspagem/raspagem/spiders/raspagem_spider.py new file mode 100644 index 0000000..29291e8 --- /dev/null +++ b/desafioAmericanas/raspagem/raspagem/spiders/raspagem_spider.py @@ -0,0 +1,45 @@ +import scrapy + + +class RaspagemSpiderSpider(scrapy.Spider): + name = 'raspagem_spider' + start_urls = ['http://quotes.toscrape.com/'] + + # def start_requests(self): + # urls = ['http://quotes.toscrape.com/'] + + # for url in urls: + # yield scrapy.Request(url=url, callback=self.parse) + + def parse(self, response, **kwargs): + # tags = [] + # listaAutor = [] + for i in response.xpath('//div[@class="quote"]'): + citacao = i.xpath('.//span[@class="text"]//text()').get() + nome = i.xpath('.//small[@class="author"]//text()').get() + url = i.xpath('.//span/a/@href').get() + + tags = [resultado for resultado in i.xpath('.//div[@class="tags"]//text()')[1:-1].getall() if resultado.strip()] + + autor = { + 'nome': nome, + 'url': url + } + # listaAutor.append(autor) + + + yield { + 'citacao': citacao, + 'autor': autor, + # 'nome': nome, + # 'url': url, + 'tags': tags + } + + NEXT_PAGE_SELECTOR = '.next a ::attr(href)' + proxima_pagina = response.css(NEXT_PAGE_SELECTOR).extract_first() + if proxima_pagina: + yield scrapy.Request( + response.urljoin(proxima_pagina), + callback=self.parse + ) \ No newline at end of file diff --git a/desafioAmericanas/raspagem/scrapy.cfg b/desafioAmericanas/raspagem/scrapy.cfg new file mode 100644 index 0000000..d424f69 --- /dev/null +++ b/desafioAmericanas/raspagem/scrapy.cfg @@ -0,0 +1,11 @@ +# Automatically created by: scrapy startproject +# +# For more information about the [deploy] section see: +# https://scrapyd.readthedocs.io/en/latest/deploy.html + +[settings] +default = raspagem.settings + +[deploy] +#url = http://localhost:6800/ +project = raspagem diff --git a/desafioAmericanas/resultadosQueryMongoDB.txt b/desafioAmericanas/resultadosQueryMongoDB.txt new file mode 100644 index 0000000..866a104 --- /dev/null +++ b/desafioAmericanas/resultadosQueryMongoDB.txt @@ -0,0 +1,99 @@ +Quantas citações foram coletadas? + +db.matheus_rodrigues.aggregate([{ $count: "citacao" }]) + +[ { citacao: 100 } ] + + + + + +Quantas tags distintas foram coletadas? + +db.matheus_rodrigues.distinct("tags").length + + +137 + + + + +Quantas citações por autor foram coletadas? + + +db.matheus_rodrigues.aggregate([{$group: {_id: "$autor", qtd: {$sum: 1} } }]) + + + + + +[ + { + _id: { nome: 'Suzanne Collins', url: '/author/Suzanne-Collins' }, + qtd: 2 + }, + { _id: { nome: 'Harper Lee', url: '/author/Harper-Lee' }, qtd: 1 }, + { _id: { nome: 'Bob Marley', url: '/author/Bob-Marley' }, qtd: 3 }, + { + _id: { nome: 'James Baldwin', url: '/author/James-Baldwin' }, + qtd: 1 + }, + { + _id: { nome: 'Charles Bukowski', url: '/author/Charles-Bukowski' }, + qtd: 2 + }, + { _id: { nome: 'John Lennon', url: '/author/John-Lennon' }, qtd: 1 }, + { + _id: { nome: 'J.D. Salinger', url: '/author/J-D-Salinger' }, + qtd: 1 + }, + { + _id: { nome: 'Mother Teresa', url: '/author/Mother-Teresa' }, + qtd: 2 + }, + { + _id: { nome: 'Stephenie Meyer', url: '/author/Stephenie-Meyer' }, + qtd: 1 + }, + { + _id: { + nome: 'Martin Luther King Jr.', + url: '/author/Martin-Luther-King-Jr' + }, + qtd: 1 + }, + { _id: { nome: 'J.M. Barrie', url: '/author/J-M-Barrie' }, qtd: 1 }, + { + _id: { nome: 'Helen Keller', url: '/author/Helen-Keller' }, + qtd: 1 + }, + { + _id: { nome: 'George Bernard Shaw', url: '/author/George-Bernard-Shaw' }, + qtd: 1 + }, + { _id: { nome: 'J.K. Rowling', url: '/author/J-K-Rowling' }, qtd: 9 }, + { + _id: { nome: 'Terry Pratchett', url: '/author/Terry-Pratchett' }, + qtd: 1 + }, + { + _id: { nome: 'E.E. Cummings', url: '/author/E-E-Cummings' }, + qtd: 1 + }, + { + _id: { nome: 'Friedrich Nietzsche', url: '/author/Friedrich-Nietzsche' }, + qtd: 1 + }, + { + _id: { nome: 'Albert Einstein', url: '/author/Albert-Einstein' }, + qtd: 10 + }, + { + _id: { nome: 'Garrison Keillor', url: '/author/Garrison-Keillor' }, + qtd: 1 + }, + { + _id: { nome: 'J.R.R. Tolkien', url: '/author/J-R-R-Tolkien' }, + qtd: 1 + } +]