Cómo crear un robot web básico con Scrapy
Los programas que leen información de páginas web o robots web tienen una variedad de aplicaciones útiles.
Escribir estos robots web es más fácil de lo que piensas. Python tiene una excelente biblioteca para escribir scripts que extraen información de páginas web. ¡Repasemos el siguiente artículo para ver cómo crear un robot web con Scrapy!
Crear un robot web con Scrapy
- Instalar Scrapy
- Cómo crear un robot web
- Deshabilitar registro
- Usar Inspector de cromo
- título de la declaración
- Buscar instrucciones
- Recopilar datos JSON
- Aprovecha muchos factores
Instalar Scrapy
Scrapy es una biblioteca de Python para escanear y construir robots web. Es rápido, simple y se puede navegar fácilmente en muchos sitios web.
Scrapy está disponible a través de Pip Install Python Library (PIP). Para obtener información sobre cómo instalar PIP, consulte el artículo: Instalación de paquetes de Python PIP en Windows, Mac y Linux.
Es preferible usar un entorno virtual de Python, ya que le permite instalar Scrapy en un directorio virtual y mantener intacto el sistema de archivos. La documentación de Scrapy recomienda que haga esto para obtener mejores resultados.
Cree un directorio e inicialice el entorno virtual.
mkdir crawler cd crawler virtualenv venv . venv/bin/activate
Ahora puede instalar Scrapy en este directorio usando el comando PIP.
pip install scrapy
Verificación rápida para asegurarse de que Scrapy esté instalado correctamente:
scrapy # prints Scrapy 1.4.0 - no active project Usage: scrapy [options] [args] Available commands: bench Run quick benchmark test fetch Fetch a URL using the Scrapy downloader genspider Generate new spider using pre-defined templates runspider Run a self-contained spider (without creating a project) .
scrapy # prints Scrapy 1.4.0 - no active project Usage: scrapy [options] [args] Available commands: bench Run quick benchmark test fetch Fetch a URL using the Scrapy downloader genspider Generate new spider using pre-defined templates runspider Run a self-contained spider (without creating a project) .
Cómo crear un robot web
Ahora que el entorno está listo, puede comenzar a crear robots web. Consulte la página de Wikipedia para obtener información sobre las baterías:
https://en.wikipedia.org/wiki/Battery_(electricity)
El primer paso para escribir un robot es definir una clase de Python que se extienda desde Araña. Esto le da acceso a toda la funcionalidad en Scrapy. Llame a esta clase Araña 1.
La clase spider necesita algo de información:
- nombre ( nombre ) para identificar arañas
- Esta URL de inicio La variable contiene una lista de URL de rastreo (las URL de Wikipedia serán ejemplos en este tutorial)
- Esta método de análisis (). Se utiliza para procesar páginas web y recuperar información.
import scrapy class spider1(scrapy.Spider): name="Wikipedia" start_urls = ['https://en.wikipedia.org/wiki/Battery_(electricity)'] def parse(self, response): pass
Una prueba rápida para asegurarse de que todo funciona correctamente.
scrapy runpider spider1.py # imprimir 23.11.2017 09:09:21 [scrapy.utils.log] INFORMACIÓN: Lanzamiento de Scrapy 1.4.0 (bot: scrapybot) 2017-11-23 09:09:21 [scrapy.utils.log] INFORMACIÓN: Cancelar configuración: {'SPIDER_LOADER_WARN_ONLY': Verdadero} 23.11.2017 09:09:21 [scrapy.middleware] Información: Extensiones permitidas: ['scrapy.extensions.memusage.MemoryUsage', 'scrapy.extensions.logstats.LogStats',
Turn off logging
Running Scrapy with this class will export log information which will not help at the moment. Make things simple by removing this redundant log information. Add the following code to the beginning of the file.
import logging logging.getLogger('scrapy').setLevel(logging.WARNING)
Now when you run the script again, the log information will not be printed.
Use Chrome Inspector
Everything on a web page is stored in HTML elements. Elements are organized in the Document Object Model (DOM). Understanding the DOM is important to make the most of the web crawler. Web crawlers search through all the HTML elements on a page to find information, so it's important to understand how they are organized.
Google Chrome has tools to help you find HTML elements faster. You can position the HTML in any element you see on the web with the inspector.
- Navigate to a page in Chrome
- Place your mouse over the element you want to see
- Right click and select Inspect from the menu
These steps will open the developer console with the Elements tab selected. At the bottom of the console, you will see a tree diagram containing the elements. This tree diagram is how you will get information for the script.
Extract title
Use the script to do some work. Gather simple information to get the site's title text.
Start the script by adding some code to the parse () method to extract the title.
. def parse(self, response): print response.css('h1#firstHeading::text').extract() .
The response argument supports a method called CSS () that selects elements from the page using the location you provide.
In this example, the element is h1.firstHeading. Adding :: text to the script is what is needed to give you the content of the element. Finally, the extract () method returns the selected element.
Run this script in Scrapy to export the title in text form.
[u'Battery (electricity)']
Buscar instrucciones
Ahora hemos extraído el texto del título. Haz más con guiones. El robot encontrará el primer párrafo después del título y recuperará esta información.
Aquí está el árbol de elementos en Chrome Developer Console:
div#mw-content-text>div>p
flecha correcta ( > ) representa una relación padre-hijo entre elementos. Esta ubicación devolverá todas las coincidencias pags artículo, incluida la descripción completa para obtener el primero pags elemento, puede escribir el siguiente código:
response.css('div#mw-content-text>div>p')[0]
Al igual que con el título, agrega :: texto para obtener el contenido de texto del elemento.
response.css('div#mw-content-text>div>p')[0].css('::text')
La expresión final utiliza refinación () Vuelve a la lista. puedes usar python entrar() Listar la función de concatenación después de completar la recuperación.
def parse(self, response): print ''.join(response.css('div#mw-content-text>div>p')[0].css('::text').extract())
¡El resultado es el primer párrafo del texto!
An electric battery is a device consisting of one or more electrochemical cells with external connections provided to power electrical devices such as flashlights, smartphones, and electric cars.[1] When a battery is supplying electric power, its positive terminal is .
Recopilar datos JSON
Scrapy puede extraer información en forma de texto, lo cual es muy útil. Scrapy también le permite ver datos de notación de objetos de JavaScript (JSON). JSON es una forma compacta de organizar la información y se usa ampliamente en el desarrollo web. JSON también funciona bien con Python.
Cuando necesite recopilar datos en formato JSON, puede usar extracción Declaraciones incrustadas en Scrapy.
Aquí se usa la nueva versión del script. extracción declaración . en lugar de tomar el primero pags elementos en formato de texto, esta declaración extraerá todos pags elementos y se organizan en formato JSON.
. def parse(self, response): for e in response.css('div#mw-content-text>div>p'): yield { 'para' : ''.join(e.css('::text').extract()).strip() } .
Ahora puedes correr Araña salida por indicación JSON documento:
scrapy runspider spider3.py -o joe.json
Ahora el script mostrará todos pags elemento.
[ {"para": "An electric battery is a device consisting of one or more electrochemical cells with external connections provided to power electrical devices such as flashlights, smartphones, and electric cars.[1] When a battery is supplying electric power, its positive terminal is the cathode and its negative terminal is the anode.[2] The terminal marked negative is the source of electrons that when connected to an external circuit will flow and deliver energy to an external device. When a battery is connected to an external circuit, electrolytes are able to move as ions within, allowing the chemical reactions to be completed at the separate terminals and so deliver energy to the external circuit. It is the movement of those ions within the battery which allows current to flow out of the battery to perform work.[3] Historically the term "battery" specifically referred to a device composed of multiple cells, however the usage has evolved additionally to include devices composed of a single cell.[4]"}, {"para": "Primary (single-use or "disposable") batteries are used once and discarded; the electrode materials are irreversibly changed during discharge. Common examples are the alkaline battery used for flashlights and a multitude of portable electronic devices. Secondary (rechargeable) batteries can be discharged and recharged multiple .
Aprovecha muchos factores
Hasta ahora, el rastreador web ha recibido el título y el tipo de elemento de la página. Scrapy también puede extraer información de diferentes tipos de elementos en scripts.
Siéntase libre de recuperar los éxitos de taquilla del fin de semana de IMDb. Esta información fue tomada de http://www.imdb.com/chart/boxoffice , en el orden de cada indicador.
Esta método de análisis (). Se pueden recuperar varios campos de una sola fila. Puede usar las herramientas para desarrolladores de Chrome para buscar elementos anidados en una hoja de cálculo.
. def parse(self, response): for e in response.css('div#boxoffice>table>tbody>tr'): yield { 'title': ''.join(e.css('td.titleColumn>a::text').extract()).strip(), 'weekend': ''.join(e.css('td.ratingColumn')[0].css('::text').extract()).strip(), 'gross': ''.join(e.css('td.ratingColumn')[1].css('span.secondaryInfo::text').extract()).strip(), 'weeks': ''.join(e.css('td.weeksColumn::text').extract()).strip(), 'image': e.css('td.posterColumn img::attr(src)').extract_first(), } .
Selector imagen Seguro imagen sí td.posterColumn. Utilice la expresión para recuperar el atributo correcto :: atributo (origen).
La ejecución de la araña devuelve JSON:
[ {"gross": "$93.8M", "weeks": "1", "weekend": "$93.8M", "image": "https://images-na.ssl-images-amazon.com/images/M/MV5BYWVhZjZkYTItOGIwYS00NmRkLWJlYjctMWM0ZjFmMDU4ZjEzXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_UY67_CR0,0,45,67_AL_.jpg", "title": "Justice League"}, {"gross": "$27.5M", "weeks": "1", "weekend": "$27.5M", "image": "https://images-na.ssl-images-amazon.com/images/M/MV5BYjFhOWY0OTgtNDkzMC00YWJkLTk1NGEtYWUxNjhmMmQ5ZjYyXkEyXkFqcGdeQXVyMjMxOTE0ODA@._V1_UX45_CR0,0,45,67_AL_.jpg", "title": "Wonder"}, {"gross": "$247.3M", "weeks": "3", "weekend": "$21.7M", "image": "https://images-na.ssl-images-amazon.com/images/M/MV5BMjMyNDkzMzI1OF5BMl5BanBnXkFtZTgwODcxODg5MjI@._V1_UY67_CR0,0,45,67_AL_.jpg", "title": "Thor: Ragnarok"}, . ]
Deja una respuesta