diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b6e4761 --- /dev/null +++ b/.gitignore @@ -0,0 +1,129 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/README.md b/README.md index c7e1306..260fc22 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,38 @@ # Desafio Webcrawler BIT + +# Considerações 🚀 + +## Rodando o projeto + +1 - Rodar o comando abaixo para instalar as dependências: + +```pip install -r requirements.txt``` + +2 - Instalar o MongoDB + +https://www.mongodb.com/try/download/community + +3 - Feita a instalação, iniciar o MongoDB (arquivo mongod.exe, ou adicionar ao PATH) + +4 - Para rodar o scrapy, no diretório do arquivo rodar o comando: + +```python +scrapy crawl quotes +``` + +## Rodando as queries + +1 - Para rodar as queries, rodar o comando abaixo para instalar as dependências do MongoDB no Node.JS: + +```npm install mongodb``` + +2 - Por fim, no diretório queries_js, rodar o comando: + +```python +node +``` + ## Sobre O desafio consiste na implementação de um _crawler_ que colete e armazene citações do site _http://quotes.toscrape.com_. diff --git a/desafiowebcrawler/desafiowebcrawler/__init__.py b/desafiowebcrawler/desafiowebcrawler/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/desafiowebcrawler/desafiowebcrawler/items.py b/desafiowebcrawler/desafiowebcrawler/items.py new file mode 100644 index 0000000..16c04b7 --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/items.py @@ -0,0 +1,14 @@ +# Define here the models for your scraped items +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/items.html + +import scrapy + + +class DesafiowebcrawlerItem(scrapy.Item): + # define the fields for your item here like: + title = scrapy.Field() + author = scrapy.Field() + tag = scrapy.Field() + pass diff --git a/desafiowebcrawler/desafiowebcrawler/middlewares.py b/desafiowebcrawler/desafiowebcrawler/middlewares.py new file mode 100644 index 0000000..1050745 --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/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 DesafiowebcrawlerSpiderMiddleware: + # 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 DesafiowebcrawlerDownloaderMiddleware: + # 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/desafiowebcrawler/desafiowebcrawler/pipelines.py b/desafiowebcrawler/desafiowebcrawler/pipelines.py new file mode 100644 index 0000000..c3c767a --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/pipelines.py @@ -0,0 +1,29 @@ +# 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 DesafiowebcrawlerPipeline(object): + + def __init__(self): + ## Conectando no mongodb + self.conn = pymongo.MongoClient( + 'localhost', + 27017 + ) + + ## Criando o banco + db = self.conn['quotestoscrape'] + ## Criando a tabela + self.collection = db['matheus_ferreira'] + #### Dropei a collection para nao duplicar os dados caso rode o scrapy duas vezes na mesma pagina + self.collection.drop() + + def process_item(self, item, spider): + self.collection.insert_one(dict(item)) + return item diff --git a/desafiowebcrawler/desafiowebcrawler/queries_js/count_distinct_authors_titles.js b/desafiowebcrawler/desafiowebcrawler/queries_js/count_distinct_authors_titles.js new file mode 100644 index 0000000..70b1fbf --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/queries_js/count_distinct_authors_titles.js @@ -0,0 +1,31 @@ +//Query para retornar o numero de titulos recuperados por autor +// Ordenados por quantidade, seguido de nome +var MongoClient = require('mongodb').MongoClient; +var url = "mongodb://localhost:27017/"; + +MongoClient.connect(url, function(err, db) { + if (err) throw err; + var dbo = db.db("quotestoscrape"); + dbo.collection('matheus_ferreira').aggregate([ + { + "$unwind": "$author.name" + }, + { + "$group": { + "_id": "$author.name", + "qtd": { + "$sum": 1 + } + } + }, + { + "$sort": {qtd: -1, _id: 1} + } + ]).toArray().then(res => { + res.forEach(post => console.log(JSON.stringify(post))); + }).catch(err => { + console.log(err) + }).finally(() => { + db.close(); + }) +}); diff --git a/desafiowebcrawler/desafiowebcrawler/queries_js/count_distinct_tags.js b/desafiowebcrawler/desafiowebcrawler/queries_js/count_distinct_tags.js new file mode 100644 index 0000000..66e27ca --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/queries_js/count_distinct_tags.js @@ -0,0 +1,31 @@ +//Query para retornar o numero de tags recuperadas + +var MongoClient = require('mongodb').MongoClient; +var url = "mongodb://localhost:27017/"; + +MongoClient.connect(url, function(err, db) { + if (err) throw err; + var dbo = db.db("quotestoscrape"); + dbo.collection('matheus_ferreira').aggregate([ + { + "$unwind": "$tag" + }, + { + "$group": { + "_id": "$tag", + "qtd": { + "$sum": 1 + } + } + }, + { + "$sort": {qtd: -1, _id: 1} + } + ]).toArray().then(res => { + res.forEach(post => console.log(JSON.stringify(post))); + }).catch(err => { + console.log(err) + }).finally(() => { + db.close(); + }) +}); diff --git a/desafiowebcrawler/desafiowebcrawler/queries_js/count_title.js b/desafiowebcrawler/desafiowebcrawler/queries_js/count_title.js new file mode 100644 index 0000000..b25df82 --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/queries_js/count_title.js @@ -0,0 +1,16 @@ +//Query para retornar o numero de titulos recuperados + +var MongoClient = require('mongodb').MongoClient; +var url = "mongodb://localhost:27017/"; + +MongoClient.connect(url, function(err, db) { + if (err) throw err; + var dbo = db.db("quotestoscrape"); + dbo.collection('matheus_ferreira').aggregate([ + { + "$count": "title" + }]).toArray().then(function(result) { + console.log("A quantidade de citações é: " + result[0].title) + }) +}); + diff --git a/desafiowebcrawler/desafiowebcrawler/settings.py b/desafiowebcrawler/desafiowebcrawler/settings.py new file mode 100644 index 0000000..a1b0dd9 --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/settings.py @@ -0,0 +1,89 @@ +# Scrapy settings for desafiowebcrawler 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 = 'desafiowebcrawler' + +SPIDER_MODULES = ['desafiowebcrawler.spiders'] +NEWSPIDER_MODULE = 'desafiowebcrawler.spiders' + + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +#USER_AGENT = 'desafiowebcrawler (+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 = { +# 'desafiowebcrawler.middlewares.DesafiowebcrawlerSpiderMiddleware': 543, +#} + +# Enable or disable downloader middlewares +# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +#DOWNLOADER_MIDDLEWARES = { +# 'desafiowebcrawler.middlewares.DesafiowebcrawlerDownloaderMiddleware': 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 +### USANDO A PIPE #### +ITEM_PIPELINES = { + 'desafiowebcrawler.pipelines.DesafiowebcrawlerPipeline': 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' diff --git a/desafiowebcrawler/desafiowebcrawler/spiders/__init__.py b/desafiowebcrawler/desafiowebcrawler/spiders/__init__.py new file mode 100644 index 0000000..ebd689a --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/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/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py b/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py new file mode 100644 index 0000000..50c242b --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py @@ -0,0 +1,55 @@ +from gc import callbacks +import scrapy +from scrapy.http import FormRequest +from scrapy.utils.response import open_in_browser +from ..items import DesafiowebcrawlerItem + +class QuotesSpider(scrapy.Spider): + name = "quotes" + start_urls = [ + 'https://quotes.toscrape.com/login' + ] + + #### Faz login na pagina + def parse(self, response): + token = response.css('form input::attr(value)').extract_first() + return FormRequest.from_response( + response, + formdata={ + 'csrf_token': token, + 'username': 'teste', + 'password': 'teste' + }, + callback=self.start + ) + + #### Inicia a coleta de dados #### + def start(self, response): + #### open_in_browser(response) abre a requisicao no navegador (bom para visualizar funcionamento) + url = 'https://quotes.toscrape.com{}' + itens = DesafiowebcrawlerItem() + # Aloca todas as divs em uma variavel + all_div_quotes = response.css("div.quote") + + # Percorre as divs iterando sobre os dados , a pipe armazena no banco + for div in all_div_quotes: + title = div.css('span.text::text').extract_first() + author = { + 'name': div.css('.author::text').extract_first(), + 'url': url.format(div.xpath( + '/html/body/div/div[2]/div[1]/div[1]/span[2]/a/@href' + ).extract_first()) + } + tag = div.css('.tag::text').extract() + + itens['title'] = title + itens['author'] = author + itens['tag'] = tag + + yield itens + + next_page = response.css('li.next a::attr(href)').get() + + if next_page is not None: + + yield response.follow(next_page, callback= self.start) \ No newline at end of file diff --git a/desafiowebcrawler/scrapy.cfg b/desafiowebcrawler/scrapy.cfg new file mode 100644 index 0000000..210a142 --- /dev/null +++ b/desafiowebcrawler/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 = desafiowebcrawler.settings + +[deploy] +#url = http://localhost:6800/ +project = desafiowebcrawler diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..ea776a1 Binary files /dev/null and b/requirements.txt differ