Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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/
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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 <filename>
```

## Sobre

O desafio consiste na implementação de um _crawler_ que colete e armazene citações do site _http://quotes.toscrape.com_.
Expand Down
Empty file.
14 changes: 14 additions & 0 deletions desafiowebcrawler/desafiowebcrawler/items.py
Original file line number Diff line number Diff line change
@@ -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
103 changes: 103 additions & 0 deletions desafiowebcrawler/desafiowebcrawler/middlewares.py
Original file line number Diff line number Diff line change
@@ -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)
29 changes: 29 additions & 0 deletions desafiowebcrawler/desafiowebcrawler/pipelines.py
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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();
})
});
Original file line number Diff line number Diff line change
@@ -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();
})
});
16 changes: 16 additions & 0 deletions desafiowebcrawler/desafiowebcrawler/queries_js/count_title.js
Original file line number Diff line number Diff line change
@@ -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)
})
});

Loading