una biblioteca conocida como beautifulsoup. Con esta biblioteca, podemos buscar los valores de las etiquetas html y recuperar datos específicos como el título de la página y la lista de títulos de la página.
Utilice el administrador de paquetes de Anaconda para instalar el paquete requerido y sus paquetes dependientes.
conda install Beaustifulsoap
En el siguiente ejemplo, estamos solicitando una URL para descargar en un entorno Python. Luego use el parámetro del analizador html para leer todo el archivo html. Luego imprimimos las primeras líneas de la página html.
import urllib2 from bs4 import BeautifulSoup # Fetch the html file response = urllib2.urlopen('https://areatutorial.com/python/python_overview.htm') html_doc = response.read() # Parse the html file soup = BeautifulSoup(html_doc, 'html.parser') # Format the parsed html file strhtm = soup.prettify() # Print the first few characters print (strhtm[:225])
Cuando ejecutamos el código anterior, da el siguiente resultado.
<!DOCTYPE html> <!--[if IE 8]><html class="ie ie8"> <![endif]--> <!--[if IE 9]><html class="ie ie9"> <![endif]--> <!--[if gt IE 9]><!--> <html> <!--<![endif]--> <head> <!-- Basic --> <meta charset="utf-8"/> <title>
Podemos extraer el valor de la etiqueta de la primera instancia de la etiqueta usando el siguiente código.
import urllib2 from bs4 import BeautifulSoup response = urllib2.urlopen('https://areatutorial.com/python/python_overview.htm') html_doc = response.read() soup = BeautifulSoup(html_doc, 'html.parser') print (soup.title) print(soup.title.string) print(soup.a.string) print(soup.b.string)
Cuando ejecutamos el código anterior, da el siguiente resultado.
Python Overview Python Overview None Python is Interpreted
Podemos extraer el valor de la etiqueta de todas las instancias de la etiqueta usando el siguiente código.
import urllib2 from bs4 import BeautifulSoup response = urllib2.urlopen('https://areatutorial.com/python/python_overview.htm') html_doc = response.read() soup = BeautifulSoup(html_doc, 'html.parser') for x in soup.find_all('b'): print(x.string)
Cuando ejecutamos el código anterior, da el siguiente resultado.
Python is Interpreted Python is Interactive Python is Object-Oriented Python is a Beginner's Language Easy-to-learn Easy-to-read Easy-to-maintain A broad standard library Interactive Mode Portable Extendable Databases GUI Programming Scalable
🚫