{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Scraping, HTML\n", "\n", "Los componentes de una página web, archivo html, css y javascript (en su forma más sencilla)" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "archivo.html\n", "\n", "\n", "
\n", "\n", "\n", "\n", "Parrafo 1\n", "
\n", "\n", "Parrafo 2\n", "
\n", "\n", "" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "archivo.css\n", "\n", " .verde{\n", "background:green;\n", "}\n", "\n", ".rojo{\n", "background:red;\n", "}\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import re\n", "import requests\n", "from bs4 import BeautifulSoup" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "b'\\n\\n\\t\\n\\t\\t\\n\\t\\t \\n\\t\\t \\n\\t\\tLos autores han hecho su mejor esfuerzo en la preparación de este material. Se distribuye gratuitamente con la esperanza de que sea útil, pero sin ninguna garantía expresa o implícita respecto a la exactitud o completitud del contenido.
',\n", " 'Este prefacio (así como todo el documento electrónico) es variante respecto al tiempo, lo que consultes dependerá de la fecha y hora en que lo hagas. Creo (no tengo una referencia que confirme lo que escribiré) que los libros usuales han sido parte de la educación por tradición, es claro que hace décadas (por no decir siglos) una de las formas de almacenar los conocimientos era escribiendo libros y claro que la experiencia de interactuar con un libro es inigualable. En la actualidad tenemos herramientas tecnológicas (tantas que no sabemos que elegir) para almacenar información, transmitir y enseña, simular situaciones, etc. Por tal motivo este \"\"libro\"\" (le llamaremos documento electrónico) es un poco diferente a lo usual. Se presenta de manera escrita la teoría, pero muchas de las explicaciones son mediante video, lo cual acota a que la consulta sea mediante un dispositivo digital (por tal motivo lo definimos como un documento electrónico).
']" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pes1=re.findall(r\"([\\s+|\\n+|\\w+]?.+
)\",str(pagina.content,'utf-8'))\n", "print(len(pes1))\n", "pes1[0:3]" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "333\n" ] }, { "data": { "text/plain": [ "[
La licencia es lo siguiente:\n",
" \n",
" Permite a otros copiar, distribuir, exhibir y ejecutar públicamente el trabajo, así como hacer y distribuir trabajos derivados con fines no comerciales pero reconociendo la autoría y sólo bajo la misma licencia o una compatible.
Señales y sistemas: una perspectiva por Rafael Martínez-Martínez se distribuye bajo una Licencia Creative Commons Atribución-NoComercial-CompartirIgual 4.0 Internacional.
Los autores han hecho su mejor esfuerzo en la preparación de este material. Se distribuye gratuitamente con la esperanza de que sea útil, pero sin ninguna garantía expresa o implícita respecto a la exactitud o completitud del contenido.
]" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "soup = BeautifulSoup(pagina.content, 'html.parser')\n", "pes=soup.findAll(\"p\")\n", "print(len(pes))\n", "pes[0:3]" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[\n", " Si \\( \\mathbb{R}e(a)>0\\) la evalución\n", " \\({ \\left. t{ e }^{ -(a+j\\omega )t } \\right| }_{ 0 }^{ \\infty }=0\\),\n", " se tiene que:
,\n", "\n", " de acuerdo a la definición de valor absoluto\n", "
,\n", "\n", " Si \\( \\mathbb{R}e(a)>0\\) las evaluciones son \\(1\\) y \\(-1\\)\n", " repectivamente, al operar el signo en el denominador de la \n", " primera expresión se tiene que:
]" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a=soup.findAll(\"p\", class_ = \"justo\")\n", "a" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "scrolled": true, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on Tag in module bs4.element object:\n", "\n", "class Tag(PageElement)\n", " | Tag(parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None, is_xml=None, sourceline=None, sourcepos=None, can_be_empty_element=None, cdata_list_attributes=None, preserve_whitespace_tags=None)\n", " | \n", " | Represents an HTML or XML tag that is part of a parse tree, along\n", " | with its attributes and contents.\n", " | \n", " | When Beautiful Soup parses the markup penguin, it will\n", " | create a Tag object representing the tag.\n", " | \n", " | Method resolution order:\n", " | Tag\n", " | PageElement\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __bool__(self)\n", " | A tag is non-None even if it has no contents.\n", " | \n", " | __call__(self, *args, **kwargs)\n", " | Calling a Tag like a function is the same as calling its\n", " | find_all() method. Eg. tag('a') returns a list of all the A tags\n", " | found within this tag.\n", " | \n", " | __contains__(self, x)\n", " | \n", " | __copy__(self)\n", " | A copy of a Tag is a new Tag, unconnected to the parse tree.\n", " | Its contents are a copy of the old Tag's contents.\n", " | \n", " | __delitem__(self, key)\n", " | Deleting tag[key] deletes all 'key' attributes for the tag.\n", " | \n", " | __eq__(self, other)\n", " | Returns true iff this Tag has the same name, the same attributes,\n", " | and the same contents (recursively) as `other`.\n", " | \n", " | __getattr__(self, tag)\n", " | Calling tag.subtag is the same as calling tag.find(name=\"subtag\")\n", " | \n", " | __getitem__(self, key)\n", " | tag[key] returns the value of the 'key' attribute for the Tag,\n", " | and throws an exception if it's not there.\n", " | \n", " | __hash__(self)\n", " | Return hash(self).\n", " | \n", " | __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None, is_xml=None, sourceline=None, sourcepos=None, can_be_empty_element=None, cdata_list_attributes=None, preserve_whitespace_tags=None)\n", " | Basic constructor.\n", " | \n", " | :param parser: A BeautifulSoup object.\n", " | :param builder: A TreeBuilder.\n", " | :param name: The name of the tag.\n", " | :param namespace: The URI of this Tag's XML namespace, if any.\n", " | :param prefix: The prefix for this Tag's XML namespace, if any.\n", " | :param attrs: A dictionary of this Tag's attribute values.\n", " | :param parent: The PageElement to use as this Tag's parent.\n", " | :param previous: The PageElement that was parsed immediately before\n", " | this tag.\n", " | :param is_xml: If True, this is an XML tag. Otherwise, this is an\n", " | HTML tag.\n", " | :param sourceline: The line number where this tag was found in its\n", " | source document.\n", " | :param sourcepos: The character position within `sourceline` where this\n", " | tag was found.\n", " | :param can_be_empty_element: If True, this tag should be\n", " | represented asSentimos las molestias. Necesitamos asegurarnos de que no eres un robot. Para obtener los mejores resultados, aseg\\xc3\\xbarate de que tu navegador acepta las cookies.
\\n