From 2c61b9fc37a2762bd9a59cb43a82d420a4552f90 Mon Sep 17 00:00:00 2001 From: ffmatheus Date: Fri, 29 Jul 2022 18:38:11 -0300 Subject: [PATCH 1/8] Generate .gitignore and req.txt --- .gitignore | 129 +++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | Bin 0 -> 28 bytes 2 files changed, 129 insertions(+) create mode 100644 .gitignore create mode 100644 requirements.txt 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/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f1d3f173bafd542ef5250cf2cecf17e9dd550b64 GIT binary patch literal 28 gcmezWub3g3p@<=op@5;1!4?RO81xv-fY^uu0C Date: Sat, 30 Jul 2022 13:22:02 -0300 Subject: [PATCH 2/8] Adding structure --- .../desafiowebcrawler/__init__.py | 0 desafiowebcrawler/desafiowebcrawler/items.py | 14 +++ .../desafiowebcrawler/middlewares.py | 103 ++++++++++++++++++ .../desafiowebcrawler/pipelines.py | 27 +++++ .../desafiowebcrawler/settings.py | 89 +++++++++++++++ .../desafiowebcrawler/spiders/__init__.py | 4 + .../desafiowebcrawler/spiders/itens.json | 12 ++ .../spiders/quotes_spider.py | 53 +++++++++ desafiowebcrawler/scrapy.cfg | 11 ++ requirements.txt | Bin 28 -> 58 bytes 10 files changed, 313 insertions(+) create mode 100644 desafiowebcrawler/desafiowebcrawler/__init__.py create mode 100644 desafiowebcrawler/desafiowebcrawler/items.py create mode 100644 desafiowebcrawler/desafiowebcrawler/middlewares.py create mode 100644 desafiowebcrawler/desafiowebcrawler/pipelines.py create mode 100644 desafiowebcrawler/desafiowebcrawler/settings.py create mode 100644 desafiowebcrawler/desafiowebcrawler/spiders/__init__.py create mode 100644 desafiowebcrawler/desafiowebcrawler/spiders/itens.json create mode 100644 desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py create mode 100644 desafiowebcrawler/scrapy.cfg 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..61f324d --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/pipelines.py @@ -0,0 +1,27 @@ +# 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['desafiowebcrawler'] + self.collection = db['quotes'] + + + def process_item(self, item, spider): + self.collection.insert_one(dict(item)) + return item 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/itens.json b/desafiowebcrawler/desafiowebcrawler/spiders/itens.json new file mode 100644 index 0000000..1104ee7 --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/spiders/itens.json @@ -0,0 +1,12 @@ +[ +{"title": ["\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d"], "author": ["Albert Einstein"], "tag": ["change", "deep-thoughts", "thinking", "world"]}, +{"title": ["\u201cIt is our choices, Harry, that show what we truly are, far more than our abilities.\u201d"], "author": ["J.K. Rowling"], "tag": ["abilities", "choices"]}, +{"title": ["\u201cThere are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.\u201d"], "author": ["Albert Einstein"], "tag": ["inspirational", "life", "live", "miracle", "miracles"]}, +{"title": ["\u201cThe person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.\u201d"], "author": ["Jane Austen"], "tag": ["aliteracy", "books", "classic", "humor"]}, +{"title": ["\u201cImperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.\u201d"], "author": ["Marilyn Monroe"], "tag": ["be-yourself", "inspirational"]}, +{"title": ["\u201cTry not to become a man of success. Rather become a man of value.\u201d"], "author": ["Albert Einstein"], "tag": ["adulthood", "success", "value"]}, +{"title": ["\u201cIt is better to be hated for what you are than to be loved for what you are not.\u201d"], "author": ["Andr\u00e9 Gide"], "tag": ["life", "love"]}, +{"title": ["\u201cI have not failed. I've just found 10,000 ways that won't work.\u201d"], "author": ["Thomas A. Edison"], "tag": ["edison", "failure", "inspirational", "paraphrased"]}, +{"title": ["\u201cA woman is like a tea bag; you never know how strong it is until it's in hot water.\u201d"], "author": ["Eleanor Roosevelt"], "tag": ["misattributed-eleanor-roosevelt"]}, +{"title": ["\u201cA day without sunshine is like, you know, night.\u201d"], "author": ["Steve Martin"], "tag": ["humor", "obvious", "simile"]} +] \ No newline at end of file diff --git a/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py b/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py new file mode 100644 index 0000000..e9a6e79 --- /dev/null +++ b/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py @@ -0,0 +1,53 @@ +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' + ] + + + 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 + ) + + def start(self, response): + #### Abre a requisicao no navegador (bom para visualizar funcionamento) + #open_in_browser(response) + + #### Inicia o scraping #### + itens = DesafiowebcrawlerItem() + + all_div_quotes = response.css("div.quote") + + for div in all_div_quotes: + title = div.css('span.text::text').extract() + author = { + 'name': div.css('.author::text').extract(), + 'link_bio': div.css('.author::attr(href)').extract(), + } + 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 index f1d3f173bafd542ef5250cf2cecf17e9dd550b64..ea776a1c6732083e9ecdc3128b79b24ddac4e654 100644 GIT binary patch delta 35 lcmb2Knjj;`#ZbUd$&kyC&ydHE4kT@X(1byc!3c;A7yxyN1)u-` delta 4 LcmcDLnIHoI0(=1j From 32c67eca82bec5bb5dd162f7c643e26741af631f Mon Sep 17 00:00:00 2001 From: "matheus.fernandes" Date: Sat, 30 Jul 2022 15:53:58 -0300 Subject: [PATCH 3/8] Adjust data structure --- .../desafiowebcrawler/pipelines.py | 5 +++-- .../spiders/quotes_spider.py | 20 ++++++++++--------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/desafiowebcrawler/desafiowebcrawler/pipelines.py b/desafiowebcrawler/desafiowebcrawler/pipelines.py index 61f324d..6a14cce 100644 --- a/desafiowebcrawler/desafiowebcrawler/pipelines.py +++ b/desafiowebcrawler/desafiowebcrawler/pipelines.py @@ -18,8 +18,9 @@ def __init__(self): ) ## Criando o banco - db = self.conn['desafiowebcrawler'] - self.collection = db['quotes'] + db = self.conn['quotestoscrape'] + ## Criando a tabela + self.collection = db['matheus_ferreira'] def process_item(self, item, spider): diff --git a/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py b/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py index e9a6e79..50c242b 100644 --- a/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py +++ b/desafiowebcrawler/desafiowebcrawler/spiders/quotes_spider.py @@ -10,7 +10,7 @@ class QuotesSpider(scrapy.Spider): '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( @@ -23,20 +23,22 @@ def parse(self, response): callback=self.start ) + #### Inicia a coleta de dados #### def start(self, response): - #### Abre a requisicao no navegador (bom para visualizar funcionamento) - #open_in_browser(response) - - #### Inicia o scraping #### + #### 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() + title = div.css('span.text::text').extract_first() author = { - 'name': div.css('.author::text').extract(), - 'link_bio': div.css('.author::attr(href)').extract(), + '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() From d197e39e5398d97377017b499a355b35bff26303 Mon Sep 17 00:00:00 2001 From: ffmatheus Date: Sat, 30 Jul 2022 22:19:36 -0300 Subject: [PATCH 4/8] Add js queries --- README.md | 9 ++++++ .../count_distinct_authors_titles.js | 31 +++++++++++++++++++ .../queries_js/count_distinct_tags.js | 31 +++++++++++++++++++ .../queries_js/count_title.js | 16 ++++++++++ 4 files changed, 87 insertions(+) create mode 100644 desafiowebcrawler/desafiowebcrawler/queries_js/count_distinct_authors_titles.js create mode 100644 desafiowebcrawler/desafiowebcrawler/queries_js/count_distinct_tags.js create mode 100644 desafiowebcrawler/desafiowebcrawler/queries_js/count_title.js diff --git a/README.md b/README.md index c7e1306..916b7df 100644 --- a/README.md +++ b/README.md @@ -58,3 +58,12 @@ Cada citação deve ser salva no _MongoDB_ seguindo o seguinte formato: Tudo pronto? Basta criar um _fork_ deste repositório e abrir um **pull request** quando finalizar ;) Em caso de dúvidas, envie um e-mail pra gente: analytics.tech@b2wdigital.com + +to install dependencies +pip install -r requirements.txt + +to run scrapy +scrapy crawl quotes + +to run queries +npm install mongodb \ No newline at end of file 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) + }) +}); + From 7c34c061c4c409b460f5a6499ea101e88c73e8d6 Mon Sep 17 00:00:00 2001 From: ffmatheus Date: Sat, 30 Jul 2022 23:45:36 -0300 Subject: [PATCH 5/8] Increase documentation on readme --- README.md | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 916b7df..75fb3f0 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,38 @@ # Desafio Webcrawler BIT + +# Considerações + +## Rodando o projeto + +Rodar o comando abaixo para instalar as dependências: + +```pip install -r requirements.txt``` + +Instalar o MongoDB + +(https://www.mongodb.com/try/download/community) + +Feita a instalação, iniciar o MongoDB (arquivo mongod.exe, ou adicionar ao PATH) + +Para rodar o scrapy, no diretório do arquivo rodar o comando: + +```python +scrapy crawl quotes +``` + +## Rodando as queries + +Para rodar as queries, rodar o comando abaixo para instalar as dependências do MongoDB no Node.JS: + +```npm install mongodb``` + +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_. @@ -58,12 +91,3 @@ Cada citação deve ser salva no _MongoDB_ seguindo o seguinte formato: Tudo pronto? Basta criar um _fork_ deste repositório e abrir um **pull request** quando finalizar ;) Em caso de dúvidas, envie um e-mail pra gente: analytics.tech@b2wdigital.com - -to install dependencies -pip install -r requirements.txt - -to run scrapy -scrapy crawl quotes - -to run queries -npm install mongodb \ No newline at end of file From ae867be7765385a11b9102a7d583683477ef60e4 Mon Sep 17 00:00:00 2001 From: ffmatheus Date: Sat, 30 Jul 2022 23:46:34 -0300 Subject: [PATCH 6/8] Adjustment on readme --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 75fb3f0..defc208 100644 --- a/README.md +++ b/README.md @@ -5,17 +5,17 @@ ## Rodando o projeto -Rodar o comando abaixo para instalar as dependências: +1 - Rodar o comando abaixo para instalar as dependências: ```pip install -r requirements.txt``` -Instalar o MongoDB +2 - Instalar o MongoDB -(https://www.mongodb.com/try/download/community) +https://www.mongodb.com/try/download/community -Feita a instalação, iniciar o MongoDB (arquivo mongod.exe, ou adicionar ao PATH) +3 - Feita a instalação, iniciar o MongoDB (arquivo mongod.exe, ou adicionar ao PATH) -Para rodar o scrapy, no diretório do arquivo rodar o comando: +4 - Para rodar o scrapy, no diretório do arquivo rodar o comando: ```python scrapy crawl quotes @@ -23,11 +23,11 @@ scrapy crawl quotes ## Rodando as queries -Para rodar as queries, rodar o comando abaixo para instalar as dependências do MongoDB no Node.JS: +1 - Para rodar as queries, rodar o comando abaixo para instalar as dependências do MongoDB no Node.JS: ```npm install mongodb``` -Por fim, no diretório queries_js, rodar o comando: +2 - Por fim, no diretório queries_js, rodar o comando: ```python node From 558a0d83aea1a3058cc1d29babab9b24bc1236f8 Mon Sep 17 00:00:00 2001 From: ffmatheus Date: Sat, 30 Jul 2022 23:54:04 -0300 Subject: [PATCH 7/8] Adjustments --- desafiowebcrawler/desafiowebcrawler/pipelines.py | 3 ++- .../desafiowebcrawler/spiders/itens.json | 12 ------------ 2 files changed, 2 insertions(+), 13 deletions(-) delete mode 100644 desafiowebcrawler/desafiowebcrawler/spiders/itens.json diff --git a/desafiowebcrawler/desafiowebcrawler/pipelines.py b/desafiowebcrawler/desafiowebcrawler/pipelines.py index 6a14cce..c3c767a 100644 --- a/desafiowebcrawler/desafiowebcrawler/pipelines.py +++ b/desafiowebcrawler/desafiowebcrawler/pipelines.py @@ -21,7 +21,8 @@ def __init__(self): 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)) diff --git a/desafiowebcrawler/desafiowebcrawler/spiders/itens.json b/desafiowebcrawler/desafiowebcrawler/spiders/itens.json deleted file mode 100644 index 1104ee7..0000000 --- a/desafiowebcrawler/desafiowebcrawler/spiders/itens.json +++ /dev/null @@ -1,12 +0,0 @@ -[ -{"title": ["\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d"], "author": ["Albert Einstein"], "tag": ["change", "deep-thoughts", "thinking", "world"]}, -{"title": ["\u201cIt is our choices, Harry, that show what we truly are, far more than our abilities.\u201d"], "author": ["J.K. Rowling"], "tag": ["abilities", "choices"]}, -{"title": ["\u201cThere are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.\u201d"], "author": ["Albert Einstein"], "tag": ["inspirational", "life", "live", "miracle", "miracles"]}, -{"title": ["\u201cThe person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.\u201d"], "author": ["Jane Austen"], "tag": ["aliteracy", "books", "classic", "humor"]}, -{"title": ["\u201cImperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.\u201d"], "author": ["Marilyn Monroe"], "tag": ["be-yourself", "inspirational"]}, -{"title": ["\u201cTry not to become a man of success. Rather become a man of value.\u201d"], "author": ["Albert Einstein"], "tag": ["adulthood", "success", "value"]}, -{"title": ["\u201cIt is better to be hated for what you are than to be loved for what you are not.\u201d"], "author": ["Andr\u00e9 Gide"], "tag": ["life", "love"]}, -{"title": ["\u201cI have not failed. I've just found 10,000 ways that won't work.\u201d"], "author": ["Thomas A. Edison"], "tag": ["edison", "failure", "inspirational", "paraphrased"]}, -{"title": ["\u201cA woman is like a tea bag; you never know how strong it is until it's in hot water.\u201d"], "author": ["Eleanor Roosevelt"], "tag": ["misattributed-eleanor-roosevelt"]}, -{"title": ["\u201cA day without sunshine is like, you know, night.\u201d"], "author": ["Steve Martin"], "tag": ["humor", "obvious", "simile"]} -] \ No newline at end of file From 19a2c1f418bcfae55902edf13b734a30022f3d71 Mon Sep 17 00:00:00 2001 From: Matheus Ferreira <55103202+ffmatheus@users.noreply.github.com> Date: Sat, 30 Jul 2022 23:56:10 -0300 Subject: [PATCH 8/8] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index defc208..260fc22 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Desafio Webcrawler BIT -# Considerações +# Considerações 🚀 ## Rodando o projeto