Editar documento HTML en Python

Espacio de nombres DOM

Aspose.HTML for Python via .NET le permite acceder y manipular el DOM HTML (modelo de objetos de documento) en lenguaje Python. El espacio de nombres aspose.html.dom proporciona una API para interactuar con documentos HTML, XML y SVG. Representa el documento como un árbol de nodos, donde cada nodo representa una parte del documento, como un elemento, una cadena de texto o un comentario. El espacio de nombres incluye clases como Attr, CharacterData, Comment y más, cada una de las cuales tiene propósitos específicos dentro del modelo de documento.

La clase Document representa el documento HTML, XML o SVG completo y sirve como raíz del árbol del documento. Otras clases como Element, Node, DocumentFragment y EventTarget brindan acceso a diferentes partes del documento y permiten la manipulación e interacción con los datos del documento. La API se basa en el estándar WHATWG DOM. Por lo tanto, es fácil usar Aspose.HTML for Python via .NET teniendo un conocimiento básico de los lenguajes HTML y JavaScript.

Editar HTML

Para editar un documento HTML usando el árbol DOM, use la clase HTMLDocument, que representa el documento completo. Hay muchas formas de editar HTML utilizando nuestra biblioteca Python. Puede modificar el documento insertando nuevos nodos, eliminando o editando el contenido de los nodos existentes. Si necesita crear un nuevo elemento o nodo, debe invocar los siguientes métodos:

Para manipular los atributos de los elementos, utilice los métodos:

Una vez que haya creado nuevos nodos, existen varios métodos en el DOM que pueden ayudarlo a insertar nodos en el árbol del documento. La siguiente lista describe la forma más común de insertar o eliminar nodos:

Para obtener una lista completa de clases y métodos representados en el espacio de nombres DOM, visite Fuente de referencia API.

Editar un árbol de documentos

Aspose.HTML Python API admite un conjunto de elementos HTML que se definen en HTML Standard, junto con reglas sobre cómo se pueden anidar los elementos. Considere pasos simples para crear HTML desde cero y editarlo usando un árbol DOM y las funciones mencionadas anteriormente. El documento contendrá un párrafo de texto con un atributo id:

Este código demuestra cómo crear un documento HTML básico mediante programación, agregar un párrafo con un atributo y texto y guardar el HTML resultante en un archivo:

 1# Edit HTML document using DOM Tree in Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Define the output directory and file path
 7output_dir = "output/"
 8output_path = os.path.join(output_dir, "edit-document-tree.html")
 9
10# Ensure the output directory exists
11os.makedirs(output_dir, exist_ok=True)
12
13# Create an instance of an HTML document
14document = ah.HTMLDocument()
15
16# Access the document <body> element
17body = document.body
18
19# Create a paragraph element <p>
20p = document.create_element("p")
21
22# Set a custom attribute
23p.set_attribute("id", "my-paragraph")
24
25# Create a text node
26text = document.create_text_node("The Aspose.Html.Dom namespace provides an API for representing and interfacing with HTML, XML, or SVG documents.")
27
28# Add the text to the paragraph
29p.append_child(text)
30
31# Attach the paragraph to the document body
32body.append_child(p)
33
34# Save the HTML document to a file
35document.save(output_path)

Veamos cómo crear un documento HTML más complejo. En el siguiente fragmento de código, construiremos un documento HTML desde cero, crearemos nuevos elementos, los rellenaremos con contenido y los agregaremos a la estructura del documento HTML. El modelo HTML DOM y la funcionalidad mencionada anteriormente nos ayudarán con esto.

 1# Create and add new HTML elements using Python
 2
 3import os
 4import aspose.html as ah
 5
 6# Define output directory and file paths
 7output_dir = "output/"
 8save_path = os.path.join(output_dir, "edit-document.html")
 9
10# Ensure the output directory exists
11os.makedirs(output_dir, exist_ok=True)
12
13# Create an instance of an HTML document
14document = ah.HTMLDocument()
15
16# Create a style element and set the teal color for elements with class "col"
17style = document.create_element("style")
18style.text_content = ".col { color: teal }"
19
20# Find the document <head> element and append the <style> element
21head = document.get_elements_by_tag_name("head")[0]
22head.append_child(style)
23
24# Create a paragraph <p> element with class "col"
25p = document.create_element("p")
26p.class_name = "col"
27
28# Create a text node
29text = document.create_text_node("Edit HTML document")
30
31# Append the text node to the paragraph
32p.append_child(text)
33
34# Append the paragraph to the document <body>
35document.body.append_child(p)
36
37# Save the HTML document to a file
38document.save(save_path)

La Fuente de referencia de API proporciona una lista completa de clases y métodos en el espacio de nombres DOM.

Usando las propiedades inner_html y outer_html

Trabajar con objetos DOM proporciona una forma poderosa de manipular un documento HTML en Python. Sin embargo, en algunos casos, puede resultar más conveniente trabajar directamente con cadenas. Las propiedades inner_html y outer_html se usan para acceder y manipular contenido HTML en un documento, pero difieren en lo que representan y cómo se usan:

  1. La propiedad inner_html representa el contenido HTML dentro de un elemento, excluyendo las etiquetas de inicio y fin del propio elemento.
  2. La propiedad outer_html representa todo el contenido HTML de un elemento, incluidas sus propias etiquetas de inicio y fin.

El siguiente fragmento de código le muestra cómo utilizar las propiedades inner_html y outer_html de la clase Element para editar HTML.

 1# Edit HTML body content and get modified document as a string using Python
 2
 3import aspose.html as ah
 4
 5# Create an instance of an HTML document
 6document = ah.HTMLDocument()
 7
 8# Write the content of the HTML document to the console
 9print(document.document_element.outer_html)  # output: <html><head></head><body></body></html>
10
11# Set the content of the body element
12document.body.inner_html = "<p>HTML is the standard markup language for Web pages.</p>"
13
14# Find the document <p> element
15p = document.get_elements_by_tag_name("p")[0]
16
17# Write the updated content of the HTML document to the console
18print(p.inner_html)  # output: HTML is the standard markup language for Web pages.
19
20# Write the updated content of the HTML document to the console
21print(document.document_element.outer_html)  # output: <html><head></head><body><p>HTML is the standard markup language for Web pages.</p></body></html>

Editar CSS

Las hojas de estilo en cascada (CSS) son un lenguaje de hojas de estilo que se utiliza para describir cómo aparecen las páginas web en un navegador. CSS se puede agregar a documentos HTML de forma en línea, interna y externa. Por lo tanto, puede definir un estilo único para un solo elemento HTML usando CSS en línea o para que varias páginas web compartan formato especificando el CSS relevante en un archivo .css separado. Aspose.HTML for Python via .NET no solo admite CSS listo para usar, sino que también le brinda instrumentos para manipular estilos de documentos sobre la marcha antes de convertir el documento HTML a otros formatos, como se muestra a continuación.

CSS en línea – Inline CSS

Cuando CSS se escribe utilizando el atributo “estilo” dentro de una etiqueta HTML, se denomina CSS en línea (inline CSS). El CSS en línea le permite aplicar un estilo individual a un elemento HTML a la vez. Puede configurar CSS para un elemento HTML utilizando el atributo “estilo” con cualquier propiedad CSS definida dentro de él. En el siguiente fragmento de código, puede ver cómo especificar propiedades de estilo CSS para un elemento HTML <p>.

 1# How to set inline CSS styles in an HTML element using Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.rendering.pdf as rp
 6
 7# Define the content of the HTML document
 8content = "<p>Edit inline CSS using Aspose.HTML for Python via .NET</p>"
 9
10# Create an instance of an HTML document with specified content
11document = ah.HTMLDocument(content, ".")
12
13# Find the paragraph element and set a style attribute
14paragraph = document.get_elements_by_tag_name("p")[0]
15paragraph.set_attribute("style", "font-size: 150%; font-family: arial; color: teal")
16
17# Save the HTML document to a file
18output_dir = "output/"
19os.makedirs(output_dir, exist_ok=True)
20html_path = os.path.join(output_dir, "edit-inline-css.html")
21document.save(html_path)
22
23# Create an instance of the PDF output device and render the document to this device
24pdf_path = os.path.join(output_dir, "edit-inline-css.pdf")
25with rp.PdfDevice(pdf_path) as device:
26    document.render_to(device)
Example-EditInlineCss.py hosted with ❤ by GitHub

En este ejemplo particular, el color, el tamaño de fuente y la familia de fuente se aplican al elemento <p>. El fragmento de la página pdf renderizada se ve así:

Texto “Editar CSS en línea”

CSS interno – Internal CSS

La opción de estilo CSS interno es popular para aplicar propiedades a páginas individuales encerrando todos los estilos en el elemento <style> colocado en el <head> de los documentos HTML.

 1# Edit HTML with internal CSS using Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.rendering.pdf as rp
 6
 7
 8# Define the content of the HTML document
 9content = "<div><h1>Internal CSS</h1><p>An internal CSS is used to define a style for a single HTML page</p></div>"
10
11# Create an instance of an HTML document with specified content
12document = ah.HTMLDocument(content, ".")
13
14# Create a <style> element and define internal CSS rules
15style = document.create_element("style")
16style.text_content = (
17    ".frame1 { margin-top:50px; margin-left:50px; padding:25px; width:360px; height:90px; "
18    "background-color:#82011a; font-family:arial; color:#fff5ee;} \r\n"
19    ".frame2 { margin-top:-70px; margin-left:160px; text-align:center; padding:20px; width:360px; "
20    "height:100px; background-color:#ebd2d7;}"
21)
22
23# Find the <head> element and append the style element
24head = document.get_elements_by_tag_name("head")[0]
25head.append_child(style)
26
27# Find the first paragraph element and apply styles
28header = document.get_elements_by_tag_name("h1")[0]
29header.class_name = "frame1"
30
31# Update the style using the style attribute directly
32header.set_attribute("style", "font-size: 200%; text-align: center;")
33
34# Find the last paragraph element and apply styles
35paragraph = document.get_elements_by_tag_name("p")[0]
36paragraph.class_name = "frame2"
37paragraph.set_attribute("style", "color: #434343; font-size: 150%; font-family: verdana;")
38
39# Save the HTML document to a file
40output_dir = "output/"
41os.makedirs(output_dir, exist_ok=True)
42html_path = os.path.join(output_dir, "edit-internal-css.html")
43document.save(html_path)
44
45# Create an instance of the PDF output device and render the document to this device
46pdf_path = os.path.join(output_dir, "edit-internal-css.pdf")
47with rp.PdfDevice(pdf_path) as device:
48    document.render_to(device)

En este ejemplo, usamos CSS interno y también declaramos propiedades de estilo adicionales para elementos individuales usando el atributo style dentro de las etiquetas <h1> y <p>. La figura ilustra el fragmento del archivo edit-internal-css.pdf renderizado:

Texto “Editar CSS interno”

Descargue la biblioteca Aspose.HTML for Python via .NET para manipular con éxito, rapidez y facilidad sus documentos HTML. La biblioteca Python puede crear, modificar, extraer datos, convertir y renderizar documentos HTML sin necesidad de software externo. Admite formatos de archivos populares como EPUB, MHTML, XML, SVG y Markdown y puede renderizar en formatos de archivos PDF, DOCX, XPS e imágenes.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.