From 6f31d52f14a60fc9f2c238802444dbb7f4a61184 Mon Sep 17 00:00:00 2001 From: Carlos Eduardo Rodrigues Date: Sat, 30 Sep 2023 21:20:36 -0300 Subject: [PATCH] [Add] Tutorial sobre o Scrapy --- docs/_sidebar.md | 7 +- docs/sprints/sprint-03/[MODELO] sprint-03.md | 10 + .../scrapy-introducao-e-instalacao.md | 178 +++++++++++ prototipos/scrapy.py | 1 - prototipos/tutorial_spyder/livros.json | 112 +++++++ prototipos/tutorial_spyder/quotes-1.html | 281 ++++++++++++++++ prototipos/tutorial_spyder/quotes-2.html | 301 ++++++++++++++++++ prototipos/tutorial_spyder/scrapy.cfg | 11 + .../tutorial_spyder/__init__.py | 0 .../tutorial_spyder/tutorial_spyder/items.py | 12 + .../tutorial_spyder/middlewares.py | 103 ++++++ .../tutorial_spyder/pipelines.py | 13 + .../tutorial_spyder/settings.py | 93 ++++++ .../tutorial_spyder/spiders/__init__.py | 4 + .../tutorial_spyder/spiders/quotes_spider.py | 21 ++ 15 files changed, 1145 insertions(+), 2 deletions(-) create mode 100644 docs/sprints/sprint-03/[MODELO] sprint-03.md create mode 100644 docs/sprints/sprint-03/scrapy-introducao-e-instalacao.md delete mode 100644 prototipos/scrapy.py create mode 100644 prototipos/tutorial_spyder/livros.json create mode 100644 prototipos/tutorial_spyder/quotes-1.html create mode 100644 prototipos/tutorial_spyder/quotes-2.html create mode 100644 prototipos/tutorial_spyder/scrapy.cfg create mode 100644 prototipos/tutorial_spyder/tutorial_spyder/__init__.py create mode 100644 prototipos/tutorial_spyder/tutorial_spyder/items.py create mode 100644 prototipos/tutorial_spyder/tutorial_spyder/middlewares.py create mode 100644 prototipos/tutorial_spyder/tutorial_spyder/pipelines.py create mode 100644 prototipos/tutorial_spyder/tutorial_spyder/settings.py create mode 100644 prototipos/tutorial_spyder/tutorial_spyder/spiders/__init__.py create mode 100644 prototipos/tutorial_spyder/tutorial_spyder/spiders/quotes_spider.py diff --git a/docs/_sidebar.md b/docs/_sidebar.md index 239885b..ca899bc 100644 --- a/docs/_sidebar.md +++ b/docs/_sidebar.md @@ -18,4 +18,9 @@ - [Retrospectiva e Análise Sprint-01](/sprints/sprint-01/retrospectiva-e-analise-sprint-01.md "Sprint-01 - Retrospectiva e Análise SPRINT-01") - **Sprint 02 (20/09 - 27/09/23)** - - [Estudo do Projeto "Querido Diário" da Open Knowledge Brasil](/sprints/sprint-02/estudo-sobre-o-projeto-querido-diario.md "Estudo do Projeto Querido Diário da Open Knowledge Brasil") \ No newline at end of file + - [Estudo do Projeto "Querido Diário" da Open Knowledge Brasil](/sprints/sprint-02/estudo-sobre-o-projeto-querido-diario.md "Estudo do Projeto Querido Diário da Open Knowledge Brasil") + + - **Sprint 03 (27/09 - 04/10/23)** + - [Introdução ao Scrapy e tutorias de instalação](/sprints/sprint-03/scrapy-introducao-e-instalacao.md "Introdução ao Scrapy e tutorias de instalação") + + - **Sprint 04 (04/10 - 11/10/23)** \ No newline at end of file diff --git a/docs/sprints/sprint-03/[MODELO] sprint-03.md b/docs/sprints/sprint-03/[MODELO] sprint-03.md new file mode 100644 index 0000000..51f940a --- /dev/null +++ b/docs/sprints/sprint-03/[MODELO] sprint-03.md @@ -0,0 +1,10 @@ +
+ Sprint 03 - Maré de Produtividade +
+
+ + +# Conteúdo da sprint vai aqui... + + +
\ No newline at end of file diff --git a/docs/sprints/sprint-03/scrapy-introducao-e-instalacao.md b/docs/sprints/sprint-03/scrapy-introducao-e-instalacao.md new file mode 100644 index 0000000..0a5d353 --- /dev/null +++ b/docs/sprints/sprint-03/scrapy-introducao-e-instalacao.md @@ -0,0 +1,178 @@ +
+ Sprint 03 - Maré de Produtividade +
+
+ + +# 📜 Introdução ao Scrapy e tutorias de instalação + +## O que é o Scrapy? 🤔 +O Scrapy é um framework de web scraping de código aberto em Python usado para extrair informações de sites da web de maneira automatizada. Web scraping é o processo de coletar dados de páginas da web de forma programática, em vez de manualmente, o que é útil para várias finalidades, como coletar dados para análise, pesquisa, mineração de dados, entre outras. + +O Scrapy fornece uma estrutura robusta e flexível para desenvolver [spiders](#nossa-primeira-spyder-🕷️), que são programas que navegam na web, fazem solicitações HTTP para páginas da web, extraem dados de interesse e armazenam esses dados em um formato estruturado, como JSON, CSV ou em um banco de dados. Além disso, o Scrapy lida com tarefas como gerenciamento de cookies, tratamento de redirecionamentos, paralelismo de solicitações e muito mais. + +**Clique** 👉 [**aqui**](https://github.com/unb-mds/2023-2-Squad04/blob/main/prototipos/tutorial_spyder/) **e tenha acesso ao nosso prototipo** + +## Instalação do Scrapy 👨‍🔧 +Para começar a usar o Scrapy, siga estas etapas para a instalação:
+**⚠️ Certifique-se de que você tenha o Python instalado em seu sistema. O Scrapy requer Python 3.8+** +1. Verificando a versão do python: `python --version` +2. Instalando o scrapy: + - Se você estiver usando Anaconda ou Miniconda, você pode instalar a partir do canal conda-forge, que possui pacotes atualizados para Linux, Windows e macOS: `conda install -c conda-forge scrapy` + - Como alternativa, se você já estiver familiarizado com a instalação de pacotes Python, você pode instalar o Scrapy e suas dependências do PyPI com: `pip install scrapy` + - Verifique a instalação: `scrapy --version`
+ + 3. ⚠️ **Em caso de erros, crie um Ambiente Virtual (Recomendado para evitar conflitos entre pacotes instalados no sistema):** + - Primeiro, crie um ambiente virtual: `python3 -m venv meuambiente` + - Ative o ambiente virtual: `source meuambiente/bin/activate` + - Instale o scrapy: `pip install scrapy` + - Para sair do ambiente virtual, basta digitar o seguinte comando: `deactivate` + + +## Exemplo de utilização do Scrapy 🧐 +Vamos raspar [quotes.toscrape.com](quotes.toscrape.com), um site que lista citações de autores famosos. + +### Nossa primeira Spyder 🕷️ + +Spiders são classes que você define e que o Scrapy usa para raspar informações de um site (ou de um grupo de sites). + +#### Criando um projeto + +Antes de começar a fazer web scraping, você precisará configurar um novo projeto Scrapy. Acesse um diretório onde você deseja armazenar seu código e execute: +`scrapy startproject tutorial` + +Isso criará um diretório com o seguinte conteúdo: +``` +tutorial/ + scrapy.cfg # arquivo de configuração para implantação + + tutorial/ # módulo Python do projeto, você importará seu código a partir daqui + __init__.py + + items.py # arquivo de definição de itens do projeto + + middlewares.py # arquivo de middlewares do projeto + + pipelines.py # arquivo de pipelines do projeto + + settings.py # arquivo de configurações do projeto + + spiders/ # um diretório onde você colocará suas spiders posteriormente + __init__.py + +``` + +Este é o código para a nossa primeira Spider. + +```python +from pathlib import Path + +import scrapy + +class QuotesSpider(scrapy.Spider): + name = "quotes" + + def start_requests(self): + urls = [ + "https://quotes.toscrape.com/page/1/", + "https://quotes.toscrape.com/page/2/", + ] + for url in urls: + yield scrapy.Request(url=url, callback=self.parse) + + def parse(self, response): + page = response.url.split("/")[-2] + filename = f"quotes-{page}.html" + Path(filename).write_bytes(response.body) + self.log(f"Saved file {filename}") +``` + +Como você pode ver, nossa Spider é uma subclasse de scrapy.Spider e define alguns atributos e métodos: + +- **name:** identifica a Spider. Ele deve ser exclusivo dentro de um projeto, ou seja, você não pode definir o mesmo nome para diferentes Spiders. + +- **start_requests():** deve retornar um iterável de Requests (você pode retornar uma lista de solicitações ou escrever uma função geradora) a partir das quais a Spider começará a rastrear. Solicitações subsequentes serão geradas sucessivamente a partir dessas solicitações iniciais. + +- **parse():** um método que será chamado para lidar com a resposta baixada para cada uma das solicitações feitas. O parâmetro de resposta é uma instância de TextResponse que contém o conteúdo da página e possui métodos adicionais úteis para lidar com ele. + +- O método **parse()** geralmente analisa a resposta, extrai os dados raspados como dicionários e também encontra novas URLs para seguir, criando novas solicitações () a partir delas. + +#### Como executar nossa spyder 💻 +Para colocar nossa spider para trabalhar, vá para o diretório de nível superior do projeto e execute:
+`scrapy crawl quotes` + +Este comando executa a spider com o nome que acabamos de adicionar, que enviará algumas solicitações para o domínio. Você receberá uma saída semelhante a esta: + +``` +... (omitted for brevity) +2016-12-16 21:24:05 [scrapy.core.engine] INFO: Spider opened +2016-12-16 21:24:05 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) +2016-12-16 21:24:05 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023 +2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (404) (referer: None) +2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None) +2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) (referer: None) +2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-1.html +2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-2.html +2016-12-16 21:24:05 [scrapy.core.engine] INFO: Closing spider (finished) +... +``` + +Agora, verifique os arquivos no diretório atual. Você deve notar que dois novos arquivos foram criados: **quotes-1.html** e **quotes-2.html**, com o conteúdo correspondente às respectivas URLs, conforme nosso método instrui. + +#### O que aconteceu nos bastidores? 🤔 + +O Scrapy agendou os objetos retornados pelo método da Spider. Ao receber uma resposta para cada um deles, ele cria objetos de Resposta e chama o método de retorno de chamada associado à solicitação (neste caso, o método "parse"), passando a resposta como argumento. + +#### Raspando apenas os dados e salvando em um .json 💾 +O código abaixo é um exemplo de uma spider que raspa dados das páginas, em vez de salvar o HTML como fazia a do exemplo anterior. + +**Clique** 👉 [**aqui**](https://github.com/unb-mds/2023-2-Squad04/blob/main/prototipos/tutorial_spyder/) **e tenha acesso ao nosso prototipo** + +``` +import scrapy + +class QuotesSpider(scrapy.Spider): + # Nome do spider + name = "quotes" + + # URLs iniciais a serem raspadas + start_urls = [ + "https://quotes.toscrape.com/page/1/", + "https://quotes.toscrape.com/page/2/", + ] + + # Função que é chamada para processar cada página + def parse(self, response): + # Loop através de cada elemento 'div.quote' na página + for quote in response.css("div.quote"): + # Extrai o texto da citação usando o seletor CSS + text = quote.css("span.text::text").get() + # Extrai o autor da citação usando o seletor CSS + author = quote.css("span small::text").get() + # Extrai todas as tags da citação usando o seletor CSS + tags = quote.css("div.tags a.tag::text").getall() + + # Cria um dicionário com os dados extraídos + quote_data = { + "text": text, + "author": author, + "tags": tags, + } + + # Retorna o dicionário como resultado do processamento da página + yield quote_data + + # Verifica se há uma próxima página + next_page = response.css("li.next a::attr(href)").get() + if next_page is not None: + # Se houver uma próxima página, segue o link e chama 'parse' novamente + yield response.follow(next_page, self.parse) + +``` +Você pode armazenar os dados extraídos em um formato de sua escolha, como JSON, CSV ou em um banco de dados. Para salvar os dados em um arquivo JSON, você pode usar o seguinte comando: `scrapy crawl livros -o livros.json` + +# 🕵️ Para saber mais... +Esse tutorial se baseou na documentação oficial do scrapy, se você quiser saber mais a fundo sobre todas as funcionalidades disponíveis da ferramenta, clique 👉 [aqui](https://docs.scrapy.org/en/latest/index.html) e acesse a documentação completa. + + +
\ No newline at end of file diff --git a/prototipos/scrapy.py b/prototipos/scrapy.py deleted file mode 100644 index 8b13789..0000000 --- a/prototipos/scrapy.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/prototipos/tutorial_spyder/livros.json b/prototipos/tutorial_spyder/livros.json new file mode 100644 index 0000000..d0a567b --- /dev/null +++ b/prototipos/tutorial_spyder/livros.json @@ -0,0 +1,112 @@ +[ + { "text": "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”", "author": "Albert Einstein", "tags": ["change", "deep-thoughts", "thinking", "world"] }, + { "text": "“It is our choices, Harry, that show what we truly are, far more than our abilities.”", "author": "J.K. Rowling", "tags": ["abilities", "choices"] }, + { "text": "“There 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.”", "author": "Albert Einstein", "tags": ["inspirational", "life", "live", "miracle", "miracles"] }, + { "text": "“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”", "author": "Jane Austen", "tags": ["aliteracy", "books", "classic", "humor"] }, + { "text": "“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”", "author": "Marilyn Monroe", "tags": ["be-yourself", "inspirational"] }, + { "text": "“Try not to become a man of success. Rather become a man of value.”", "author": "Albert Einstein", "tags": ["adulthood", "success", "value"] }, + { "text": "“It is better to be hated for what you are than to be loved for what you are not.”", "author": "André Gide", "tags": ["life", "love"] }, + { "text": "“I have not failed. I've just found 10,000 ways that won't work.”", "author": "Thomas A. Edison", "tags": ["edison", "failure", "inspirational", "paraphrased"] }, + { "text": "“A woman is like a tea bag; you never know how strong it is until it's in hot water.”", "author": "Eleanor Roosevelt", "tags": ["misattributed-eleanor-roosevelt"] }, + { "text": "“A day without sunshine is like, you know, night.”", "author": "Steve Martin", "tags": ["humor", "obvious", "simile"] }, + { "text": "“This life is what you make it. No matter what, you're going to mess up sometimes, it's a universal truth. But the good part is you get to decide how you're going to mess it up. Girls will be your friends - they'll act like it anyway. But just remember, some come, some go. The ones that stay with you through everything - they're your true best friends. Don't let go of them. Also remember, sisters make the best friends in the world. As for lovers, well, they'll come and go too. And baby, I hate to say it, most of them - actually pretty much all of them are going to break your heart, but you can't give up because if you give up, you'll never find your soulmate. You'll never find that half who makes you whole and that goes for everything. Just because you fail once, doesn't mean you're gonna fail at everything. Keep trying, hold on, and always, always, always believe in yourself, because if you don't, then who will, sweetie? So keep your head high, keep your chin up, and most importantly, keep smiling, because life's a beautiful thing and there's so much to smile about.”", "author": "Marilyn Monroe", "tags": ["friends", "heartbreak", "inspirational", "life", "love", "sisters"] }, + { "text": "“It takes a great deal of bravery to stand up to our enemies, but just as much to stand up to our friends.”", "author": "J.K. Rowling", "tags": ["courage", "friends"] }, + { "text": "“If you can't explain it to a six year old, you don't understand it yourself.”", "author": "Albert Einstein", "tags": ["simplicity", "understand"] }, + { "text": "“You may not be her first, her last, or her only. She loved before she may love again. But if she loves you now, what else matters? She's not perfect—you aren't either, and the two of you may never be perfect together but if she can make you laugh, cause you to think twice, and admit to being human and making mistakes, hold onto her and give her the most you can. She may not be thinking about you every second of the day, but she will give you a part of her that she knows you can break—her heart. So don't hurt her, don't change her, don't analyze and don't expect more than she can give. Smile when she makes you happy, let her know when she makes you mad, and miss her when she's not there.”", "author": "Bob Marley", "tags": ["love"] }, + { "text": "“I like nonsense, it wakes up the brain cells. Fantasy is a necessary ingredient in living.”", "author": "Dr. Seuss", "tags": ["fantasy"] }, + { "text": "“I may not have gone where I intended to go, but I think I have ended up where I needed to be.”", "author": "Douglas Adams", "tags": ["life", "navigation"] }, + { "text": "“The opposite of love is not hate, it's indifference. The opposite of art is not ugliness, it's indifference. The opposite of faith is not heresy, it's indifference. And the opposite of life is not death, it's indifference.”", "author": "Elie Wiesel", "tags": ["activism", "apathy", "hate", "indifference", "inspirational", "love", "opposite", "philosophy"] }, + { "text": "“It is not a lack of love, but a lack of friendship that makes unhappy marriages.”", "author": "Friedrich Nietzsche", "tags": ["friendship", "lack-of-friendship", "lack-of-love", "love", "marriage", "unhappy-marriage"] }, + { "text": "“Good friends, good books, and a sleepy conscience: this is the ideal life.”", "author": "Mark Twain", "tags": ["books", "contentment", "friends", "friendship", "life"] }, + { "text": "“Life is what happens to us while we are making other plans.”", "author": "Allen Saunders", "tags": ["fate", "life", "misattributed-john-lennon", "planning", "plans"] }, + { "text": "“This life is what you make it. No matter what, you're going to mess up sometimes, it's a universal truth. But the good part is you get to decide how you're going to mess it up. Girls will be your friends - they'll act like it anyway. But just remember, some come, some go. The ones that stay with you through everything - they're your true best friends. Don't let go of them. Also remember, sisters make the best friends in the world. As for lovers, well, they'll come and go too. And baby, I hate to say it, most of them - actually pretty much all of them are going to break your heart, but you can't give up because if you give up, you'll never find your soulmate. You'll never find that half who makes you whole and that goes for everything. Just because you fail once, doesn't mean you're gonna fail at everything. Keep trying, hold on, and always, always, always believe in yourself, because if you don't, then who will, sweetie? So keep your head high, keep your chin up, and most importantly, keep smiling, because life's a beautiful thing and there's so much to smile about.”", "author": "Marilyn Monroe", "tags": ["friends", "heartbreak", "inspirational", "life", "love", "sisters"] }, + { "text": "“It takes a great deal of bravery to stand up to our enemies, but just as much to stand up to our friends.”", "author": "J.K. Rowling", "tags": ["courage", "friends"] }, + { "text": "“If you can't explain it to a six year old, you don't understand it yourself.”", "author": "Albert Einstein", "tags": ["simplicity", "understand"] }, + { "text": "“You may not be her first, her last, or her only. She loved before she may love again. But if she loves you now, what else matters? She's not perfect—you aren't either, and the two of you may never be perfect together but if she can make you laugh, cause you to think twice, and admit to being human and making mistakes, hold onto her and give her the most you can. She may not be thinking about you every second of the day, but she will give you a part of her that she knows you can break—her heart. So don't hurt her, don't change her, don't analyze and don't expect more than she can give. Smile when she makes you happy, let her know when she makes you mad, and miss her when she's not there.”", "author": "Bob Marley", "tags": ["love"] }, + { "text": "“I like nonsense, it wakes up the brain cells. Fantasy is a necessary ingredient in living.”", "author": "Dr. Seuss", "tags": ["fantasy"] }, + { "text": "“I may not have gone where I intended to go, but I think I have ended up where I needed to be.”", "author": "Douglas Adams", "tags": ["life", "navigation"] }, + { "text": "“The opposite of love is not hate, it's indifference. The opposite of art is not ugliness, it's indifference. The opposite of faith is not heresy, it's indifference. And the opposite of life is not death, it's indifference.”", "author": "Elie Wiesel", "tags": ["activism", "apathy", "hate", "indifference", "inspirational", "love", "opposite", "philosophy"] }, + { "text": "“It is not a lack of love, but a lack of friendship that makes unhappy marriages.”", "author": "Friedrich Nietzsche", "tags": ["friendship", "lack-of-friendship", "lack-of-love", "love", "marriage", "unhappy-marriage"] }, + { "text": "“Good friends, good books, and a sleepy conscience: this is the ideal life.”", "author": "Mark Twain", "tags": ["books", "contentment", "friends", "friendship", "life"] }, + { "text": "“Life is what happens to us while we are making other plans.”", "author": "Allen Saunders", "tags": ["fate", "life", "misattributed-john-lennon", "planning", "plans"] }, + { "text": "“I love you without knowing how, or when, or from where. I love you simply, without problems or pride: I love you in this way because I do not know any other way of loving but this, in which there is no I or you, so intimate that your hand upon my chest is my hand, so intimate that when I fall asleep your eyes close.”", "author": "Pablo Neruda", "tags": ["love", "poetry"] }, + { "text": "“For every minute you are angry you lose sixty seconds of happiness.”", "author": "Ralph Waldo Emerson", "tags": ["happiness"] }, + { "text": "“If you judge people, you have no time to love them.”", "author": "Mother Teresa", "tags": ["attributed-no-source"] }, + { "text": "“Anyone who thinks sitting in church can make you a Christian must also think that sitting in a garage can make you a car.”", "author": "Garrison Keillor", "tags": ["humor", "religion"] }, + { "text": "“Beauty is in the eye of the beholder and it may be necessary from time to time to give a stupid or misinformed beholder a black eye.”", "author": "Jim Henson", "tags": ["humor"] }, + { "text": "“Today you are You, that is truer than true. There is no one alive who is Youer than You.”", "author": "Dr. Seuss", "tags": ["comedy", "life", "yourself"] }, + { "text": "“If you want your children to be intelligent, read them fairy tales. If you want them to be more intelligent, read them more fairy tales.”", "author": "Albert Einstein", "tags": ["children", "fairy-tales"] }, + { "text": "“It is impossible to live without failing at something, unless you live so cautiously that you might as well not have lived at all - in which case, you fail by default.”", "author": "J.K. Rowling", "tags": [] }, + { "text": "“Logic will get you from A to Z; imagination will get you everywhere.”", "author": "Albert Einstein", "tags": ["imagination"] }, + { "text": "“One good thing about music, when it hits you, you feel no pain.”", "author": "Bob Marley", "tags": ["music"] }, + { "text": "“The more that you read, the more things you will know. The more that you learn, the more places you'll go.”", "author": "Dr. Seuss", "tags": ["learning", "reading", "seuss"] }, + { "text": "“Of course it is happening inside your head, Harry, but why on earth should that mean that it is not real?”", "author": "J.K. Rowling", "tags": ["dumbledore"] }, + { "text": "“The truth is, everyone is going to hurt you. You just got to find the ones worth suffering for.”", "author": "Bob Marley", "tags": ["friendship"] }, + { "text": "“Not all of us can do great things. But we can do small things with great love.”", "author": "Mother Teresa", "tags": ["misattributed-to-mother-teresa", "paraphrased"] }, + { "text": "“To the well-organized mind, death is but the next great adventure.”", "author": "J.K. Rowling", "tags": ["death", "inspirational"] }, + { "text": "“All you need is love. But a little chocolate now and then doesn't hurt.”", "author": "Charles M. Schulz", "tags": ["chocolate", "food", "humor"] }, + { "text": "“We read to know we're not alone.”", "author": "William Nicholson", "tags": ["misattributed-to-c-s-lewis", "reading"] }, + { "text": "“Any fool can know. The point is to understand.”", "author": "Albert Einstein", "tags": ["knowledge", "learning", "understanding", "wisdom"] }, + { "text": "“I have always imagined that Paradise will be a kind of library.”", "author": "Jorge Luis Borges", "tags": ["books", "library"] }, + { "text": "“It is never too late to be what you might have been.”", "author": "George Eliot", "tags": ["inspirational"] }, + { "text": "“A reader lives a thousand lives before he dies, said Jojen. The man who never reads lives only one.”", "author": "George R.R. Martin", "tags": ["read", "readers", "reading", "reading-books"] }, + { "text": "“You can never get a cup of tea large enough or a book long enough to suit me.”", "author": "C.S. Lewis", "tags": ["books", "inspirational", "reading", "tea"] }, + { "text": "“You believe lies so you eventually learn to trust no one but yourself.”", "author": "Marilyn Monroe", "tags": [] }, + { "text": "“If you can make a woman laugh, you can make her do anything.”", "author": "Marilyn Monroe", "tags": ["girls", "love"] }, + { "text": "“Life is like riding a bicycle. To keep your balance, you must keep moving.”", "author": "Albert Einstein", "tags": ["life", "simile"] }, + { "text": "“The real lover is the man who can thrill you by kissing your forehead or smiling into your eyes or just staring into space.”", "author": "Marilyn Monroe", "tags": ["love"] }, + { "text": "“A wise girl kisses but doesn't love, listens but doesn't believe, and leaves before she is left.”", "author": "Marilyn Monroe", "tags": ["attributed-no-source"] }, + { "text": "“Only in the darkness can you see the stars.”", "author": "Martin Luther King Jr.", "tags": ["hope", "inspirational"] }, + { "text": "“It matters not what someone is born, but what they grow to be.”", "author": "J.K. Rowling", "tags": ["dumbledore"] }, + { "text": "“Love does not begin and end the way we seem to think it does. Love is a battle, love is a war; love is a growing up.”", "author": "James Baldwin", "tags": ["love"] }, + { "text": "“There is nothing I would not do for those who are really my friends. I have no notion of loving people by halves, it is not my nature.”", "author": "Jane Austen", "tags": ["friendship", "love"] }, + { "text": "“Do one thing every day that scares you.”", "author": "Eleanor Roosevelt", "tags": ["attributed", "fear", "inspiration"] }, + { "text": "“I am good, but not an angel. I do sin, but I am not the devil. I am just a small girl in a big world trying to find someone to love.”", "author": "Marilyn Monroe", "tags": ["attributed-no-source"] }, + { "text": "“If I were not a physicist, I would probably be a musician. I often think in music. I live my daydreams in music. I see my life in terms of music.”", "author": "Albert Einstein", "tags": ["music"] }, + { "text": "“If you only read the books that everyone else is reading, you can only think what everyone else is thinking.”", "author": "Haruki Murakami", "tags": ["books", "thought"] }, + { "text": "“The difference between genius and stupidity is: genius has its limits.”", "author": "Alexandre Dumas fils", "tags": ["misattributed-to-einstein"] }, + { "text": "“He's like a drug for you, Bella.”", "author": "Stephenie Meyer", "tags": ["drug", "romance", "simile"] }, + { "text": "“There is no friend as loyal as a book.”", "author": "Ernest Hemingway", "tags": ["books", "friends", "novelist-quotes"] }, + { "text": "“When one door of happiness closes, another opens; but often we look so long at the closed door that we do not see the one which has been opened for us.”", "author": "Helen Keller", "tags": ["inspirational"] }, + { "text": "“Life isn't about finding yourself. Life is about creating yourself.”", "author": "George Bernard Shaw", "tags": ["inspirational", "life", "yourself"] }, + { "text": "“That's the problem with drinking, I thought, as I poured myself a drink. If something bad happens you drink in an attempt to forget; if something good happens you drink in order to celebrate; and if nothing happens you drink to make something happen.”", "author": "Charles Bukowski", "tags": ["alcohol"] }, + { "text": "“You don’t forget the face of the person who was your last hope.”", "author": "Suzanne Collins", "tags": ["the-hunger-games"] }, + { "text": "“Remember, we're madly in love, so it's all right to kiss me anytime you feel like it.”", "author": "Suzanne Collins", "tags": ["humor"] }, + { "text": "“To love at all is to be vulnerable. Love anything and your heart will be wrung and possibly broken. If you want to make sure of keeping it intact you must give it to no one, not even an animal. Wrap it carefully round with hobbies and little luxuries; avoid all entanglements. Lock it up safe in the casket or coffin of your selfishness. But in that casket, safe, dark, motionless, airless, it will change. It will not be broken; it will become unbreakable, impenetrable, irredeemable. To love is to be vulnerable.”", "author": "C.S. Lewis", "tags": ["love"] }, + { "text": "“Not all those who wander are lost.”", "author": "J.R.R. Tolkien", "tags": ["bilbo", "journey", "lost", "quest", "travel", "wander"] }, + { "text": "“Do not pity the dead, Harry. Pity the living, and, above all those who live without love.”", "author": "J.K. Rowling", "tags": ["live-death-love"] }, + { "text": "“There is nothing to writing. All you do is sit down at a typewriter and bleed.”", "author": "Ernest Hemingway", "tags": ["good", "writing"] }, + { "text": "“Finish each day and be done with it. You have done what you could. Some blunders and absurdities no doubt crept in; forget them as soon as you can. Tomorrow is a new day. You shall begin it serenely and with too high a spirit to be encumbered with your old nonsense.”", "author": "Ralph Waldo Emerson", "tags": ["life", "regrets"] }, + { "text": "“I have never let my schooling interfere with my education.”", "author": "Mark Twain", "tags": ["education"] }, + { "text": "“I have heard there are troubles of more than one kind. Some come from ahead and some come from behind. But I've bought a big bat. I'm all ready you see. Now my troubles are going to have troubles with me!”", "author": "Dr. Seuss", "tags": ["troubles"] }, + { "text": "“If I had a flower for every time I thought of you...I could walk through my garden forever.”", "author": "Alfred Tennyson", "tags": ["friendship", "love"] }, + { "text": "“Some people never go crazy. What truly horrible lives they must lead.”", "author": "Charles Bukowski", "tags": ["humor"] }, + { "text": "“The trouble with having an open mind, of course, is that people will insist on coming along and trying to put things in it.”", "author": "Terry Pratchett", "tags": ["humor", "open-mind", "thinking"] }, + { "text": "“Think left and think right and think low and think high. Oh, the thinks you can think up if only you try!”", "author": "Dr. Seuss", "tags": ["humor", "philosophy"] }, + { "text": "“What really knocks me out is a book that, when you're all done reading it, you wish the author that wrote it was a terrific friend of yours and you could call him up on the phone whenever you felt like it. That doesn't happen much, though.”", "author": "J.D. Salinger", "tags": ["authors", "books", "literature", "reading", "writing"] }, + { "text": "“The reason I talk to myself is because I’m the only one whose answers I accept.”", "author": "George Carlin", "tags": ["humor", "insanity", "lies", "lying", "self-indulgence", "truth"] }, + { "text": "“You may say I'm a dreamer, but I'm not the only one. I hope someday you'll join us. And the world will live as one.”", "author": "John Lennon", "tags": ["beatles", "connection", "dreamers", "dreaming", "dreams", "hope", "inspirational", "peace"] }, + { "text": "“I am free of all prejudice. I hate everyone equally. ”", "author": "W.C. Fields", "tags": ["humor", "sinister"] }, + { "text": "“The question isn't who is going to let me; it's who is going to stop me.”", "author": "Ayn Rand", "tags": [] }, + { "text": "“′Classic′ - a book which people praise and don't read.”", "author": "Mark Twain", "tags": ["books", "classic", "reading"] }, + { "text": "“Anyone who has never made a mistake has never tried anything new.”", "author": "Albert Einstein", "tags": ["mistakes"] }, + { "text": "“A lady's imagination is very rapid; it jumps from admiration to love, from love to matrimony in a moment.”", "author": "Jane Austen", "tags": ["humor", "love", "romantic", "women"] }, + { "text": "“Remember, if the time should come when you have to make a choice between what is right and what is easy, remember what happened to a boy who was good, and kind, and brave, because he strayed across the path of Lord Voldemort. Remember Cedric Diggory.”", "author": "J.K. Rowling", "tags": ["integrity"] }, + { "text": "“I declare after all there is no enjoyment like reading! How much sooner one tires of any thing than of a book! -- When I have a house of my own, I shall be miserable if I have not an excellent library.”", "author": "Jane Austen", "tags": ["books", "library", "reading"] }, + { "text": "“There are few people whom I really love, and still fewer of whom I think well. The more I see of the world, the more am I dissatisfied with it; and every day confirms my belief of the inconsistency of all human characters, and of the little dependence that can be placed on the appearance of merit or sense.”", "author": "Jane Austen", "tags": ["elizabeth-bennet", "jane-austen"] }, + { "text": "“Some day you will be old enough to start reading fairy tales again.”", "author": "C.S. Lewis", "tags": ["age", "fairytales", "growing-up"] }, + { "text": "“We are not necessarily doubting that God will do the best for us; we are wondering how painful the best will turn out to be.”", "author": "C.S. Lewis", "tags": ["god"] }, + { "text": "“The fear of death follows from the fear of life. A man who lives fully is prepared to die at any time.”", "author": "Mark Twain", "tags": ["death", "life"] }, + { "text": "“A lie can travel half way around the world while the truth is putting on its shoes.”", "author": "Mark Twain", "tags": ["misattributed-mark-twain", "truth"] }, + { "text": "“I believe in Christianity as I believe that the sun has risen: not only because I see it, but because by it I see everything else.”", "author": "C.S. Lewis", "tags": ["christianity", "faith", "religion", "sun"] }, + { "text": "“The truth.\" Dumbledore sighed. \"It is a beautiful and terrible thing, and should therefore be treated with great caution.”", "author": "J.K. Rowling", "tags": ["truth"] }, + { "text": "“I'm the one that's got to die when it's time for me to die, so let me live my life the way I want to.”", "author": "Jimi Hendrix", "tags": ["death", "life"] }, + { "text": "“To die will be an awfully big adventure.”", "author": "J.M. Barrie", "tags": ["adventure", "love"] }, + { "text": "“It takes courage to grow up and become who you really are.”", "author": "E.E. Cummings", "tags": ["courage"] }, + { "text": "“But better to get hurt by the truth than comforted with a lie.”", "author": "Khaled Hosseini", "tags": ["life"] }, + { "text": "“You never really understand a person until you consider things from his point of view... Until you climb inside of his skin and walk around in it.”", "author": "Harper Lee", "tags": ["better-life-empathy"] }, + { "text": "“You have to write the book that wants to be written. And if the book will be too difficult for grown-ups, then you write it for children.”", "author": "Madeleine L'Engle", "tags": ["books", "children", "difficult", "grown-ups", "write", "writers", "writing"] }, + { "text": "“Never tell the truth to people who are not worthy of it.”", "author": "Mark Twain", "tags": ["truth"] }, + { "text": "“A person's a person, no matter how small.”", "author": "Dr. Seuss", "tags": ["inspirational"] }, + { "text": "“... a mind needs books as a sword needs a whetstone, if it is to keep its edge.”", "author": "George R.R. Martin", "tags": ["books", "mind"] } +] \ No newline at end of file diff --git a/prototipos/tutorial_spyder/quotes-1.html b/prototipos/tutorial_spyder/quotes-1.html new file mode 100644 index 0000000..321fc55 --- /dev/null +++ b/prototipos/tutorial_spyder/quotes-1.html @@ -0,0 +1,281 @@ + + + + + Quotes to Scrape + + + + +
+
+ +
+

+ + Login + +

+
+
+ + +
+
+ +
+ “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.” + by + (about) + +
+ Tags: + + + change + + deep-thoughts + + thinking + + world + +
+
+ +
+ “It is our choices, Harry, that show what we truly are, far more than our abilities.” + by + (about) + +
+ Tags: + + + abilities + + choices + +
+
+ +
+ “There 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.” + by + (about) + +
+ Tags: + + + inspirational + + life + + live + + miracle + + miracles + +
+
+ +
+ “The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.” + by + (about) + +
+ Tags: + + + aliteracy + + books + + classic + + humor + +
+
+ +
+ “Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.” + by + (about) + +
+ Tags: + + + be-yourself + + inspirational + +
+
+ +
+ “Try not to become a man of success. Rather become a man of value.” + by + (about) + +
+ Tags: + + + adulthood + + success + + value + +
+
+ +
+ “It is better to be hated for what you are than to be loved for what you are not.” + by + (about) + +
+ Tags: + + + life + + love + +
+
+ +
+ “I have not failed. I've just found 10,000 ways that won't work.” + by + (about) + +
+ Tags: + + + edison + + failure + + inspirational + + paraphrased + +
+
+ +
+ “A woman is like a tea bag; you never know how strong it is until it's in hot water.” + by + (about) + + +
+ +
+ “A day without sunshine is like, you know, night.” + by + (about) + +
+ Tags: + + + humor + + obvious + + simile + +
+
+ + +
+
+ +

Top Ten tags

+ + + love + + + + inspirational + + + + life + + + + humor + + + + books + + + + reading + + + + friendship + + + + friends + + + + truth + + + + simile + + + +
+
+ +
+ + + \ No newline at end of file diff --git a/prototipos/tutorial_spyder/quotes-2.html b/prototipos/tutorial_spyder/quotes-2.html new file mode 100644 index 0000000..a3fe301 --- /dev/null +++ b/prototipos/tutorial_spyder/quotes-2.html @@ -0,0 +1,301 @@ + + + + + Quotes to Scrape + + + + +
+
+ +
+

+ + Login + +

+
+
+ + +
+
+ +
+ “This life is what you make it. No matter what, you're going to mess up sometimes, it's a universal truth. But the good part is you get to decide how you're going to mess it up. Girls will be your friends - they'll act like it anyway. But just remember, some come, some go. The ones that stay with you through everything - they're your true best friends. Don't let go of them. Also remember, sisters make the best friends in the world. As for lovers, well, they'll come and go too. And baby, I hate to say it, most of them - actually pretty much all of them are going to break your heart, but you can't give up because if you give up, you'll never find your soulmate. You'll never find that half who makes you whole and that goes for everything. Just because you fail once, doesn't mean you're gonna fail at everything. Keep trying, hold on, and always, always, always believe in yourself, because if you don't, then who will, sweetie? So keep your head high, keep your chin up, and most importantly, keep smiling, because life's a beautiful thing and there's so much to smile about.” + by + (about) + +
+ Tags: + + + friends + + heartbreak + + inspirational + + life + + love + + sisters + +
+
+ +
+ “It takes a great deal of bravery to stand up to our enemies, but just as much to stand up to our friends.” + by + (about) + +
+ Tags: + + + courage + + friends + +
+
+ +
+ “If you can't explain it to a six year old, you don't understand it yourself.” + by + (about) + +
+ Tags: + + + simplicity + + understand + +
+
+ +
+ “You may not be her first, her last, or her only. She loved before she may love again. But if she loves you now, what else matters? She's not perfect—you aren't either, and the two of you may never be perfect together but if she can make you laugh, cause you to think twice, and admit to being human and making mistakes, hold onto her and give her the most you can. She may not be thinking about you every second of the day, but she will give you a part of her that she knows you can break—her heart. So don't hurt her, don't change her, don't analyze and don't expect more than she can give. Smile when she makes you happy, let her know when she makes you mad, and miss her when she's not there.” + by + (about) + +
+ Tags: + + + love + +
+
+ +
+ “I like nonsense, it wakes up the brain cells. Fantasy is a necessary ingredient in living.” + by + (about) + +
+ Tags: + + + fantasy + +
+
+ +
+ “I may not have gone where I intended to go, but I think I have ended up where I needed to be.” + by + (about) + +
+ Tags: + + + life + + navigation + +
+
+ +
+ “The opposite of love is not hate, it's indifference. The opposite of art is not ugliness, it's indifference. The opposite of faith is not heresy, it's indifference. And the opposite of life is not death, it's indifference.” + by + (about) + +
+ Tags: + + + activism + + apathy + + hate + + indifference + + inspirational + + love + + opposite + + philosophy + +
+
+ +
+ “It is not a lack of love, but a lack of friendship that makes unhappy marriages.” + by + (about) + + +
+ +
+ “Good friends, good books, and a sleepy conscience: this is the ideal life.” + by + (about) + +
+ Tags: + + + books + + contentment + + friends + + friendship + + life + +
+
+ +
+ “Life is what happens to us while we are making other plans.” + by + (about) + +
+ Tags: + + + fate + + life + + misattributed-john-lennon + + planning + + plans + +
+
+ + +
+
+ +

Top Ten tags

+ + + love + + + + inspirational + + + + life + + + + humor + + + + books + + + + reading + + + + friendship + + + + friends + + + + truth + + + + simile + + + +
+
+ +
+ + + \ No newline at end of file diff --git a/prototipos/tutorial_spyder/scrapy.cfg b/prototipos/tutorial_spyder/scrapy.cfg new file mode 100644 index 0000000..669520b --- /dev/null +++ b/prototipos/tutorial_spyder/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 = tutorial_spyder.settings + +[deploy] +#url = http://localhost:6800/ +project = tutorial_spyder diff --git a/prototipos/tutorial_spyder/tutorial_spyder/__init__.py b/prototipos/tutorial_spyder/tutorial_spyder/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/prototipos/tutorial_spyder/tutorial_spyder/items.py b/prototipos/tutorial_spyder/tutorial_spyder/items.py new file mode 100644 index 0000000..4338959 --- /dev/null +++ b/prototipos/tutorial_spyder/tutorial_spyder/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 TutorialSpyderItem(scrapy.Item): + # define the fields for your item here like: + # name = scrapy.Field() + pass diff --git a/prototipos/tutorial_spyder/tutorial_spyder/middlewares.py b/prototipos/tutorial_spyder/tutorial_spyder/middlewares.py new file mode 100644 index 0000000..1a611c5 --- /dev/null +++ b/prototipos/tutorial_spyder/tutorial_spyder/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 TutorialSpyderSpiderMiddleware: + # 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 TutorialSpyderDownloaderMiddleware: + # 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/prototipos/tutorial_spyder/tutorial_spyder/pipelines.py b/prototipos/tutorial_spyder/tutorial_spyder/pipelines.py new file mode 100644 index 0000000..3eb2ae6 --- /dev/null +++ b/prototipos/tutorial_spyder/tutorial_spyder/pipelines.py @@ -0,0 +1,13 @@ +# 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 + + +class TutorialSpyderPipeline: + def process_item(self, item, spider): + return item diff --git a/prototipos/tutorial_spyder/tutorial_spyder/settings.py b/prototipos/tutorial_spyder/tutorial_spyder/settings.py new file mode 100644 index 0000000..8e25417 --- /dev/null +++ b/prototipos/tutorial_spyder/tutorial_spyder/settings.py @@ -0,0 +1,93 @@ +# Scrapy settings for tutorial_spyder 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 = "tutorial_spyder" + +SPIDER_MODULES = ["tutorial_spyder.spiders"] +NEWSPIDER_MODULE = "tutorial_spyder.spiders" + + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +#USER_AGENT = "tutorial_spyder (+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 = { +# "tutorial_spyder.middlewares.TutorialSpyderSpiderMiddleware": 543, +#} + +# Enable or disable downloader middlewares +# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +#DOWNLOADER_MIDDLEWARES = { +# "tutorial_spyder.middlewares.TutorialSpyderDownloaderMiddleware": 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 = { +# "tutorial_spyder.pipelines.TutorialSpyderPipeline": 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" + +# Set settings whose default value is deprecated to a future-proof value +REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7" +TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor" +FEED_EXPORT_ENCODING = "utf-8" diff --git a/prototipos/tutorial_spyder/tutorial_spyder/spiders/__init__.py b/prototipos/tutorial_spyder/tutorial_spyder/spiders/__init__.py new file mode 100644 index 0000000..ebd689a --- /dev/null +++ b/prototipos/tutorial_spyder/tutorial_spyder/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/prototipos/tutorial_spyder/tutorial_spyder/spiders/quotes_spider.py b/prototipos/tutorial_spyder/tutorial_spyder/spiders/quotes_spider.py new file mode 100644 index 0000000..19cce57 --- /dev/null +++ b/prototipos/tutorial_spyder/tutorial_spyder/spiders/quotes_spider.py @@ -0,0 +1,21 @@ +import scrapy + +class QuotesSpider(scrapy.Spider): + name = "quotes" + + start_urls = [ + "https://quotes.toscrape.com/page/1/", + "https://quotes.toscrape.com/page/2/", + ] + + def parse(self, response): + for quote in response.css("div.quote"): + yield { + "text": quote.css("span.text::text").get(), + "author": quote.css("span small::text").get(), + "tags": quote.css("div.tags a.tag::text").getall(), + } + + next_page = response.css("li.next a::attr(href)").get() + if next_page is not None: + yield response.follow(next_page, self.parse)