No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Curso de Scrapy

Curso de Scrapy

Facundo García Martoni

Facundo García Martoni

Scrapy Shell

8/27
Recursos

Aportes 133

Preguntas 4

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

o inicia sesión.

scrapy shell 'https://chess.com'
response.xpath('//h1[@class="guest-title"]/text()').get()

>>>  '\n      Play and Learn Chess on the #1 Site\n    '

Resumen
■■■■■■■

Scrapy tiene una consola interactiva que permite realizar pruebas, puedes testear código de manera más rápida sin necesidad de correr todo un spider, es decir, sin necesidad de volver a hacer un request, una carga de la configuración de todo el spider.

Puede usarse para probar la extracción de datos y o cualquier script. Este shell se usa para probar expresiones de CSS o Xpath de manera que es posible ir escribiendo el spider de manera más amigable.


'
Para acceder a la consola primero se hace: scrapy shell [url/path]. El parámetro de url es opcional y también puede usarse como si fuera una consola interactiva de python, puedo llamar archivos locales como una copia del sitio que quiero scrapear para probar en esta copia del HTML


# UNIX-style
scrapy shell ./path/to/file.html
scrapy shell ../other/path/to/file.html
scrapy shell /absolute/path/to/file.html

# File URI
scrapy shell file:///absolute/path/to/file.html

Nota:

  • Existen diferentes comando dentro de este shell, que son objetos que me permitirá realzar acciones útiles, como visualizar la respuesta view(response) y hacer fetch.

  • Reto: Expresión Xpath de una página Web.

response.xpath('//span[@class="central-textlogo__image sprite svg-Wikipedia_wordmark"]/text()').get()

Sigo haciendo un proyecto para extraer los ticker symbols de las acciones y todos sus estados financieros para hacer una aplicación que muestre el Fair Value
He extraído el título de la página y los tikcer que muestra pero aún no sé como avanzar a los siguientes, por el momento sn 500

scrapy shell = 'https://stockanalysis.com/stocks/'
response.xpath('//h1[1]/text()').get()
response.xpath('//tbody//td[1]/a/text()').getall()
view(response)    View response in a browser
>>> response.xpath("//h1/text()").get()
'How Big Tech Makes Their Billions'```
scrapy shell 'https://letterboxd.com/'
response.xpath('//h1[@class="site-logo"]/a[@href="/" and @class="logo replace"]/text()').get()
>>> 'Letterboxd — Your life in film'

Accedí a la web de Xataka y obtuve la última notica del día.

response.xpath('//article[@class="hero-poster poster-article m-featured"]/header/h2/a/text()').getall()

La respuesta del sitio fue:
[‘Hoy es el día límite para activar la ubicación principal en Netflix: qué pasa a partir de ahora’]

Scrapy shell "https://www.aulafacil.com/todos-los-certificados-gratis"

>>> response.xpath('//ul/li/ul/li/a/text()').getall()

[‘Todos los cursos’, ‘Idiomas’, ‘Inglés’, ‘Francés’, ‘Alemán’, ‘Italiano’, ‘Portugués’, ‘Informática’, ‘Crear Páginas Web’, ‘Excel, Word, Powerpoint, Access’, ‘Internet’, ‘Manualidades’, ‘Autoayuda’, ‘Empresa’, ‘Emprender’, ‘Contabilidad’, ‘Marketing’, ‘Cocina’, ‘Ciencia’, ‘Matemáticas’, ‘Arte / Humanidades’, ‘Aficiones’, ‘Salud’, ‘Deporte’, ‘Dibujo / Pintura’, ‘Docencia’, ‘Decoración’, ‘Belleza’, ‘Bricolaje’, ‘Bebé’, ‘Psicología’, ‘Psicología’, ‘Primaria’, ‘Secundaria ESO’, ‘Matemáticas Secundaria ESO’, ‘Lenguaje Secundaria ESO’, ‘Bachillerato’, ‘Matemáticas’, ‘Seguridad y Prevención’, ‘Otros Cursos’, ‘Arquitectura’, ‘Todos los cursos’, ‘Idiomas’, ‘Inglés’, ‘Francés’, ‘Alemán’, ‘Italiano’, ‘Portugués’, ‘Informática’, ‘Crear Páginas Web’, ‘Excel, Word, Powerpoint, Access’, ‘Internet’, ‘Manualidades’, ‘Autoayuda’, ‘Empresa’, ‘Emprender’, ‘Contabilidad’, ‘Marketing’, ‘Cocina’, ‘Ciencia’, ‘Matemáticas’, ‘Arte / Humanidades’, ‘Aficiones’, ‘Salud’, ‘Deporte’, ‘Dibujo / Pintura’, ‘Docencia’, ‘Decoración’, ‘Belleza’, ‘Bricolaje’, ‘Bebé’, ‘Psicología’, ‘Psicología’, ‘Primaria’, ‘Secundaria ESO’, ‘Matemáticas Secundaria ESO’, ‘Lenguaje Secundaria ESO’, ‘Bachillerato’, ‘Matemáticas’, ‘Seguridad y Prevención’, ‘Otros Cursos’, ‘Arquitectura’]

scrapy shell 'https://www.exito.com/celular-apple-mq2g3bea-1-tb-negro-3103358/p'

 response.xpath('//span[@class="vtex-store-components-3-x-productBrand "]/text()').get()

>>> 'iPhone 14 Pro 1 TB Negro'

scrapy shell 'https://www.visualcapitalist.com/'

response.xpath('//div[@class = "mvp-feat5-small-sub left relative"]//a/h2/text()').getall()

>>> ['Mapping the World’s Forests: How Green is Our Globe?', 'Visualizing China’s Dominance in Battery Manufacturing (2022-2027P)', 'Which Countries are the Most Polarized?', 'The Periodic Table of Commodity Returns (2013-2022)', 'Visualizing the World’s Top 25 Fleets of Combat Tanks', 'What’s Behind The Rise Of Food Prices?'] <<<

👾✨

Expresión para obtener todos los titutlos de la página principal de la resvista cambio
response.xpath(’//h2[@class=“sc-1kkixbw-0 GcYdA”]/text()’).getall()

Me traje ‘The free Encyclopedia’ de Wikipedia con la expresión:

response.xpath('//strong[@class="jsl10n localized-slogan"]/text()').get() 

Reto de la clase

  1. Para conectarse con el sitio web
scrapy shell 'https://openai.com/blog/tags/announcements/'
  1. Consulta al sitio web
response.xpath('/html/body/div[2]/div[1]/div/div[2]/div/h5/a/text()').get()

# Output: 
'New and Improved Embedding Model'
scrapy shell "https://laduchafria.com"
response.xpath('//title/text()').get()
SCRAPY SHELL = "https://fastapi.tiangolo.com/"

>>> response.xpath('//article[@class="md-content__inner md-typeset"]/h1/text()').get()

RESPONSE -> FASTAPI

no se si es lo ideal pero para temas practicos, donde se inspecciona, le pueden dar copiar xpath y es mas facil de seguir el curso asi

po acá mi aporte soy de Venezuela y me parece importante extraer del Banco Central de Venezuela el precio del dolar del día y resultó genial por aca el codigo

 scrapy shell "https://www.bcv.org.ve/"

luego de ejecutar este comando se escribe en xpath así:

response.xpath('//*[@id="dolar"]/div/div/div[2]/strong/text()').get()

Mi aporte

>>> response.xpath('//div/h1[@id="n2-ss-2item2"]/text()').get()
'La casa del fútbol inglés'

Un sitio muy interesante para aprender python es aprendepython en este caso voy a obtener el titulo de su vista principal

scrapy shell 'https://aprendepython.es/'

 response.xpath('//section[@id="aprende-python"]/h1/text()').get() 

Out[4]: 'Aprende Python'
scrapy shell 'https://skills.ia.center/explore/fase-2-aprende-comptia-security-comptia-security-f'

response.xpath('//h2[@class="course-title"]/text()').get()
scrapy shell 'https://www.levelup.com/'

response.xpath('//span[@class="brand levelup"]/a/text()').get()

'LevelUp'

response.xpath(’//a[@class=“mobile-header-title expandable”]/div/text()’).getall()

No tenia una página en mente, así que use mi portafolio personal 😄

scrapy shell “https://es.aliexpress.com/

response.xpath(’//span[@class=“logo-base”]/text()’).get()

ingresando a:
la pagina web del banco bcp de mi pais, aqu mi codigo xpath

response.xpath('//h1[@class="bcp_titulo"]/text()').get()
'\n                        ▒Gana 15,000 soles semanales por retirar tu AFP!\n  

Este fue el código Usado para extraer desde la consola de scrapy un titulo de la web el tiempo.

scrapy shell "eltiempo.com"

 response.xpath('//h3/a[@id="m1219-3-1220" and @class="title page-link"]/text()').get()

El resultado del titulo fue : “La carta los chats sobre los millonarios líos en el aeropuerto del café”

Mi aporte

scrapy shell "https://pandas.pydata.org/"

response.xpath('//section[@class="h-30 p-5 bg-light border rounded-3 text-center mb-4"]/h1/text()').get()

# Output: Pandas

Reto superado.
Scrapy de titulos a xataka

  • La URL es:
    https://developer.mozilla.org/es/

  • El Xpath es:
    response.xpath(’//div[@class=“featured-articles”]/h2/text()’).get()

  • Con el anterior Xpath se obtiene un título específico de una vista en específico del sistio web que se puso anteriormente

reto

scrapy shell 'https://www.rottentomatoes.com/m/the_batman'
response.xpath('//h1[@slot="title"]/text()').get()

Challenge Accepted:

https://spartangeek.com

response.xpath('//h2[@class="f2-ns f3 w-80-ns w-100 mb0"]/text()').get()

Un verdadero Gamer no tiene cualquier PC tiene una Spartana

Aquí mi reto:
https://www.w3schools.com/python/default.asp

response.xpath('//div[@id="leftmenuinnerinner"]/a[@target="_top"]/text()').getall()
scrapy shell "https://www.duellinksmeta.com/articles/tournaments/kc-cup/april-2022/report" 

Reto aceptado :v

scrapy shell https://es.wikipedia.org/wiki/Provincias_de_Ecuador

In [0]: response.xpath('//div[@class="mw-body"]/h1/text()').get()
Out[0]: 'Provincias de Ecuador'

También se puede traer la primera cita de Einstein con:

response.xpath(’//div[@class=“col-md-8”]//span[@class=“text”]/text()’).get()

scrapy shell "https://elperuano.pe/"

response.xpath("//span[@class='card-title2']/a/@href").get()

me sale NADA, mientras en en Chrome con map(x => x.value) me sale toda una lista

Reto:
Ir a un sitio web (ecommerce) y extraer títulos de productos

scrappy shell "https://tucentralonline.com/Bello-Monte-08/tienda"

response.xpath('//h3[@class="woocommerce-loop-product__title"]/text()').getall()

Solución al ejercicio:
Entrar a scrapy shell:

scrapy shell 'https://taiwintea.com/the-best-cities-to-live-in-taiwan/'

Extraer título

response.xpath('//header[@class="entry-header clr"]/h1[@class="single-post-title entry-title"]/text()').get()

# Output:
# 'Best Cities to Live in Taiwan – Top 10 Ranked'

Scrapy shell es una herramienta de línea de comandos que permite a los desarrolladores probar el analizador sin necesidad de utilizar el rastreador.

La liga:

De esta pagina, deseaba extraer los datos de los personajes que usaba el jugador, no hallé la manera de extraer el dato aislado ya que había más datos que cumplían con el Xpath, en este caso tener un //a/@title.

Este seria el codigo

response.xpath('//div[@class ="infobox-cell-2"]/a/@title').getall() 

Una manera de aislar el dato de los personajes sería haciendo un predicado con un operador que compruebe el valor de la data del nodo en este caso

‘Main Agents:’

Del nodo

<div class="infobox-cell-2 infobox-description">Main Agents:</div>

pero no encontre la manera de hacerlo, si es que me podrian ayudar estaré muy agradecido

Pues yo intenté sacar el titulo de esta clase xD

… solo que no sé por que no me lo trae cuando uso scrapy:

Sin embargo, cuando uso xpath directamente en la consola del navegador si me lo retorna correctamente:

así que como fracasé con eso lo hice directamente del home de platzi:

scrapy shell 'https://lichess.org/@/Nachoeigu'

response.xpath('//span[@class="offline user-link"]/text()').get()

Hola

scrapy shell 'https://www.platzi.com'
response.xpath('//h1[@class="Hero-title"]')
response.xpath('//h1[@class="Hero-title"]/text()').get()

'**Fórmate online como profesional en tecnología**'

😄

Coin Market Cap
Shel

scrapy shell 'https://coinmarketcap.com/'

Xpath

# Obtener el nombre de las criptomendas
response.xpath('//div[@class="sc-16r8icm-0 sc-1teo54s-1 dNOTPP"]/p[@class="sc-1eb5slv-0 iworPT"]/text()').getall()

# Obtener el precio de las criptomonedas
response.xpath('//div[@class="sc-131di3y-0 cLgOOr"]/a[@class="cmc-link"]/text()').getall()
scrapy shell "https://docs.python.org/es/3/library/index.html"

>>response.xpath('//div[@class="section"]/h1/text()').get()
'La Biblioteca Estándar de Python'

URL:

>>> scrapy shell 'https://platzi.com/'

Xpath:

response.xpath('//aside[@class="SchoolsList-content"]/a[@class="SchoolsList-school"]//p/strong/text()').getall()

Resultado:

['Desarrollo Web', 'JavaScript', 'Platzi English Academy', 'Marketing Digital', 'Publicidad Digital', 'Startups', 'Periodismo Digital', 'Product Design', 'Videojuegos', 'Business Management', 'Finanzas e Inversiones', 'E-Commerce y Negocios Digitales', 'Cloud Computing con Azure', 'Data Science', 'Diseño Gráfico', 'Blockchain y Criptomonedas', 'Matemáticas', 'Producción Audiovisual', 'Habilidades Blandas', 'Programación y Desarrollo de Software']

De una página que me gusta leer acerca de física, aunque poco entienda como la cuántica😂:

❯ scrapy shell 'https://eltamiz.com/'

Título de la página:

>>> response.xpath('//h1/a/text()').get()
'El Tamiz'

Títulos de las entradas:

Fechas de las entradas:

scrapy shell "https://pablomunoziturrieta.com/"
>>> response.xpath('//h1[@class="site-title"]/a/text()').get()
'Pablo Muñoz Iturrieta'
>>>
> scrapy.exe shell "https://www.sisterno.com/"

>>>response.xpath('//section[@id="hero"]/h1/text()').get()
scrapy shell "https://www.jackdaniels.com/es/whiskey/tennessee-fire"

>>response.xpath("//h1/text()").get()
'Tennessee Fire'

>>response.xpath("//h2/text()").get()
'EL CALOR DE LA CANELA, EXCEPCIONALMENTE SUAVE.'


scrapy shell "https://platzi.com"

response.xpath('//div[@class="SchoolsList-content"]/a/@href').getall()


Scrape article titles in the first page of Dev_to

$ scrapy shell "https://dev_to/"
>>> response.xpath('//h2[@class="crayons-story__title"]/a/text()').getall()

Aqui esta mi aporte

scrapy shell 'https://www.python.org/'

response.xpath('//a[@class="current_item selectedcurrent_branch selected"]/text()').get()

>>'Python'
scrapy shell 'https://www.dataquest.io/blog/free-datasets-for-projects/'

response.xpath('//h1/span[@class="thrive-shortcode-content"]/text()').get()

response.xpath('//section[@class="tcb-post-content tcb-shortcode thrv_wrapper"]/p/text()').get()
scrapy shell 'https://es.wikipedia.org/wiki/Día_del_Niño'   
response.xpath('//h1[@id="firstHeading"]/text()').get()

Returns

'Día del Niño'
scrapy shell 'https://www.marketwatch.com/'
response.xpath('//h3[@class="article__headline"]/a/text()').get()
#'\r\n                            \r\n                            Dogecoin copycats are driving up Ethereum fees and vexing parts of the crypto community\r\n

scrapy shell ‘https://depor.com


response.xpath('//h1/a[@class="extraordinary-l-score__title-link text-white title-md font-bold line-h-xs"]/text()').get()

probando vi que se puede usar for statement en la shell asi que guardando una serie de titulos de publicaciones de The gradient sería:

>>> y=0
>>> for i in x:
...     y+=1
...     print("Publications")
...     print(f"{y}) {i.strip()}")
... 
Publications
1) Why Skin Lesions are Peanuts and Brain Tumors Harder Nuts
Publications
2) The Gap: Where Machine Learning Education Falls Short    
Publications
3) How the Police Use AI to Track and Identify You
Publications
4) AI Democratization in the Era of GPT-3
Publications
5) Transformers are Graph Neural Networks
Publications
6) Shortcuts: How Neural Networks Love to Cheat
Publications
7) How to Stop Worrying About Compositionality
Publications
8) Challenges of Comparing Human and Machine Perception     
Publications
9) Lessons from the PULSE Model and Discussion
Publications
10) A Speech-To-Text Practitioner’s Criticisms of Industry and Academia
Publications
11) Towards an ImageNet Moment for Speech-to-Text

Reto completado:

scrapy shell 'https://cristianrincon.co'
response.xpath('//div/h1[@class="hestia-title"]/text()').get()```
scrapy shell 'https://starcraft2.com/en-us/'

response.xpath('//div[@class="ActionBox-content"]/h2[@class="ActionBox-heading Hero-heading"]/text()').get()
scrapy shell 'https://platzi.com/'
 response.xpath('//div[@class="HeroContent-title"]/h1/span/text()').get
()
>>> 'La escuela online de formación profesional en tecnología'
In [1]: request.url
Out[1]: 'https://platzi.com'

In [2]: response.xpath('//div[@class="HomeCategories"]//div[@class="Home
   ...: Categories-category"]/h2/text()').getall()
Out[2]:
['Negocios y emprendimiento',
 'Crecimiento Profesional',
 'Producción Audiovisual',
 'Marketing',
 'Desarrollo e ingeniería',
 'Startups',
 'Diseño y UX']
scrapy shell "https://www.metal-archives.com/bands/Evergrey/1388"

response.xpath('//h1[@class="band_name"]/a/text()').get()

'Evergrey'

Obtengo la lista de secciones de el periodico el tiempo, a la fecha

scrapy shell 'https://www.eltiempo.com/'

response.xpath('//div[@class="menu_principal2"]/ul[@class="default-menu"]/li[@itemprop="name"]/a/text()').getall()

output: ['Opinión', 'Colombia', 'Bogotá', 'Internacional', 'Política', 'Justicia', 'Economía', 'Deportes', 'Cultura', 'Tecnología', 'Vida', 'Salud', 'Unidad Investigativa', 'El Tiempo Play']
scrapy shell "https://www.marca.com/futbol/atletico/2020/09/29/5f720627ca4741de108b45ba.html"

In [1]: response.xpath('//div[@class="titles"]/h1[starts-with(@id, "t") and @class
   ...: ="js-headline izquierda"]/text()').getall()
Out[1]: ['El gol del Atlético, más repartido que nunca']

Acá use scrapy para sacar el titulo de un portfolio que estoy haciendo en github pages

scrapy shell 'https://anthonyperniah.github.io/'
response.xpath('//div[@class="container"]//p/text()').get()

Si visito la url de x sitio, me sale la web sin problemas, pero si lo hago con scrapy shell “sitio”, me devuelve error 404. Qué puede pasar? la url es esta https://www.lajuana.cl/mapa-del-sitio-la-juana-growshop-web

scrapy shell 'https://www.elespectador.com/'
response.xpath('//div[contains(@class,"Card")]//h1[@class="Card_CustomLabel"]/text()').get()
scrapy shell 'https://es.khanacademy.org/'
response.xpath('//span[@class="_1gf4zc3"]/text()').get()
# 'Para cada alumno, '

No es mi pagina favorita… pero para darle continuidad al curso anterior:

scrapy shell https://www.larepublica.co/
response.xpath('//h2[@class="headline"]/a/text()').get()

De esta manera se extraen todos los titulos de un sitio de divulgación cientifica

scrapy shell 'http://www.robotitus.com/'

>>response.xpath('//h2[@class="post-title"]/a/text()').getall()```

Con Platzi…

>>>scrapy shell "https://platzi.com/"
>>>response.xpath('//h1/span/text()').get()
'La escuela online de formación profesional en tecnología'

de el expectador.com
response.xpath(’//h1[@class=“Card_CustomLabel”]/text()’).get()
‘En Colombia la gente muere por COVID-19 menos que en otros países latinos, ¿por qué?’

scrapy shell "https://www.ole.com.ar/"
response.xpath('//h2[@class="entry-title"]/a[@target="_self"]/text()').get()

'\nPergolini: Tevez-Bermúdez, los pases y "este tarado"\n'

Zen de Python

scrapy shell 'http://www.python.org.ar/wiki/PythonZen' 
response.xpath('//ol/li/text()').getall()

En el reto utilice la consola y extrai el titulo

scrapy shell "https://scrapy.org/"

 response.xpath('//div[@class="download-stripe"]/p/text()').getall()

El resultado fue:

[' ', ' Scrapy 2.2.0 ']

Reto 2 :
Tip: Primero salir de la sesion anterior con ** Ctrl + D**

scrapy shell 'triunico.com'
response.xpath('//div [@class="h4 text-center"]/text()').get()

scrapy shell https://www.prensa.com/
response.xpath(’//h3[@class=“main-box-group-title”]/span/text()’).get()
‘Covid-19, una amenaza mundial’

scrapy shell "https://www.amazon.com.mx/" response.xpath('//h2[@class]/text()').guetall() ['EnvÝo Gratis en tu primer pedido elegible', 'Compra por Habitaci¾n', 'Favoritos de Amazon Estados Unidos', 'Inicia sesi¾n para vivir tu mejor experiencia', 'Herramientas y mßs', 'Muebles AmazonBasics', 'Vive al mßximo la tecnologÝa con Samsung', 'Cßmaras Seguridad', 'Drones y accesorios', 'Tienda de Cßmara y FotografÝa', 'Descubre la tienda oficial de Looney Tunes', 'Explora electr¾nicos como nuevos', 'Discos y Vinilos', 'Tus recuerdos al momento', 'Libros para el regreso a clases', 'Descubre artÝculos de reposterÝa']

scrapy shell "https://www.autocosmos.com.ec/catalogo"
 response.xpath('//p[@class = "multi-link-card__header-marca"]/text()').get()
scrapy shell 'https://www.memedeportes.com/ultimos/p/1'
response.xpath('//h2/a/text()').get()

scrapy shell 'https://www.xataka.com' 

>>> response.xpath('//h2/a/text()').getall()

['El timo de los sorteos de autocaravanas en Facebook: el fraude online de moda que no ha dejado de captar víctimas este verano', 'SEAT MÓ, el servicio de motosharing de SEAT, se estrena en Barcelona con más de 600 eScooters y medidas de higiene ante el COVID', 'Amazon Halo: la pulsera fitness de Amazon tiene una app que analiza nuestra grasa corporal con un modelo 3D de nuestro cuerpo', 'Por qué pagar por un medio digital si Internet da información gratis: cuatro suscriptores nos explican sus razones', 'Cómo sincronizar TODO (archivos, marcadores, contraseñas...) entre varios PCs con Windows 10', 'Las mejores apps para tu Smart TV LG con WebOS', 'De vuelta al amor por los formatos físicos', 'Este asombroso concepto soviético de hogar conectado de 1987 nos muestra como los rusos estaban muy adelantados a su época', "'Cobra Kai': así se creó la excelente secuela de 'Karate Kid' que llega a Netflix ", 'El Spectrum sigue demostrándonos su enorme potencial: estos siete juegos recientes son espectaculares y logran exprimir su hardware', 'Que el WiFi llegase a mi cuarto era toda una odisea, así que probé a instalar un PLC: esta ha sido mi experiencia', 'Guía de compra de dispositivos y accesorios tecnológicos para la vuelta a clase', 'Xataka Selección', 'Las freidoras sin aceite que en realidad no son freidoras: la psicología detrás de vendernos algo nuevo como algo conocido', '21 páginas para descargar música gratis para poder usar en tus vídeos y otros proyectos', 'Dubai Creek Tower, así es la torre que se propone superar al Burj Khalifa y convertirse en la estructura más alta del mundo', 'Ciclismo a 54 km/h sin pedalear: la ciencia que explica las propiedades aerodinámicas del pelotón', 'Xataka ', 'Un wearable para el cerebro: Neuralink muestra su primer dispositivo funcional para leer la actividad del sistema nervioso', "Papel gráfico, lápiz y el mar: lo que los bocetos originales de 'Space Invaders' cuentan del juego", 'La Tierra atraviesa una nebulosa desconocida, pero ya tenemos una pista sólida acerca de su origen: parece proceder de una supernova', 'Así es el Celera 500L, un curioso avión con forma de bala que busca ser más aerodinámico y consumir menos combustible', 'Xataka Basics', "El Xiaomi Mi 10T Pro apunta a ser el primer móvil 'no gamer' con tasa de refresco de 144 Hz, según las filtraciones", 'Google ha alcanzado otro hito en computación cuántica: ha realizado la primera simulación cuántica de una reacción química', 'Bella Thorne ha ganado 1 millón de dólares en 24 horas con su OnlyFans y eso es un "problema" para el resto de creadores ', 'Los estrenos de HBO España en septiembre 2020: todas las nuevas series, películas y documentales']

Retos (Dos ejemplos):

Rick and Morty

$ scrapy shell 'https://rickandmortyapi.com/'
response.xpath('//main/section/h1/text()').get()
# 'The Rick and Morty API'


SpaceX

$ scrapy shell 'https://www.spacex.com/'
response.xpath('//div[@id="wrapper"]/div[@id="scroller"]/div[@id="feature"]//h1/text()').get()   
# 'ANASIS-II Mission'

response.xpath('//div[@id="wrapper"]/div[@id="scroller"]/div[@class="section"]//h2/text()').get()
# 'Returning Human Spaceflight to the United States'

(200) <GET https://www.cmfchile.cl/> (referer: None)

response.xpath(’//h2/a/text()’)
[<Selector xpath=’//h2/a/text()’ data=‘Valores y Seguros’>, <Selector xpath=’//h2/a/text()’ data=‘Bancos e Instituciones Financieras’>]

response.xpath(’//h2/a/text()’).getall()
[‘Valores y Seguros’, ‘Bancos e Instituciones Financieras’]

![](

Esta clase fue genial, en el curso anterior me pareció tedioso, pero es cul entender de qué esta hablando el profesor.

scrapy shell 'https://tioanime.com/directorio'
response.xpath('//*[@class="title"]/text()').getall()

['Koi to Producer: EVOL×LOVE', 'Gibiate', 'Kanojo, Okarishimasu', 'Uzaki-chan wa Asobitai!', 'Yahari Ore no Seishun Love Comedy wa Machigatteiru. Kan', 'Peter Grill to Kenja no Jikan', 'No Guns Life 2nd Season', 'Deca-Dence', 'Re:Zero kara Hajimeru Isekai Seikatsu 2nd Season', 'Muhyo to Rouji no Mahouritsu Soudan Jimusho 2nd Season', 'Umayon\t', 'The God of High School\t', 'Maou Gakuin no Futekigousha', 'Monster Musume no Oishasan', 'Lapis Re:LiGHTs', 'Dokyuu Hentai HxEros', 'Enen no Shouboutai: Ni no Shou', 'Baki: Dai Raitaisai-hen ', 'A3! Season Spring & Summer', 'Kitsutsuki Tanteidokoro']

scrapy shell "https://www.elespectador.com/"

response.xpath('//div[@class="Card-title card-title h5"]/a/h3/text()').get()

'▒Los jueces han permitido que los intereses pol▒ticos dicten sentencia▒: Lina Moreno'

Lo hice con mi página personal 8carlosshb.com) y obtuve el título “Higlight projects” usando: response.xpath(’//h1[@class=“text-center mb-2”]/text()’).get()

![](

Comparto mis notas de este curso, espero sean de utilidad

https://github.com/rb-one/Curso-Scrapy/blob/master/Notes/notes.md

Cualquier cosa en pueda ayudar no duden en contactarme por twitter @rusbelbermudez

Tambien funciona si no se le agrega comillas.

scrapy shell http://quotes.toscrape.com/
scrapy shell https://www.eltiempo.com/salud/coronavirus-casos-de-contagio-muertes-y-ultimas-noticias-de-hoy-21-de-agosto-531910
response.xpath('//div/h1[@class="titulo" and @itemprop="headline"]/text()').get()
scrapy shell 'https://planetpython.org/'

In [5]: response.xpath('//h3[@class="post"]/a/text()').getall()
Out[5]: 
['Python Morsels',
 'IslandT',
 'Andrea Grandi',
 'Codementor',
 'Ram Rachum',
 '"CodersLegacy"',
 'Awesome Python Applications',
 'ABlog for Sphinx',
 'Awesome Python Applications',
 'Weekly Python StackOverflow Report',
 'Andrea Grandi',
 'Catalin George Festila',
 'Codementor',
 'IslandT',
 'Catalin George Festila',
 'Full Stack Python',
 'ABlog for Sphinx',
 'PyATL Bytecode',
 'Python Engineering at Microsoft',
 'Stack Abuse',
 'Andrew Dalke',
 'Real Python',
 'Talk Python to Me',
 'Python Bytes']

scrapy shell 'https://www.letour.fr/en/'

In [5]: response.xpath('//h1 [@class="banner__heading"]/text()').get().replace(' ','').replace('\n','')
Out[5]: 'Enjoythebestmomentsof2020TourdeFrance'
>>> fetch('https://realpython.com/')
<GET .........>
>>> response.xpath('//h1/text()').get()
'Real Python Tutorials'

Con fetch(url) podemos cambiar hacia donde apunta Scrapy