PDFs de páginas web con Selenium y Python

Guía rápida para imprimir páginas web a PDF con Selenium y Python: configurar Chrome, usar PrintOptions y guardar PDFs para informes empresariales.

14 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Introducción: Imprimir páginas web a PDF es una tarea habitual para generar informes, guardar facturas o archivar contenido. Con Selenium y Python se puede automatizar este flujo de forma fiable y reproducible, ideal para soluciones de software a medida y aplicaciones empresariales.

Requisitos: Python 3.8 o superior, Google Chrome instalado y el paquete selenium 4.x. También es útil contar con conocimientos básicos de manipulación de ficheros y base64 en Python.

Paso 1 Configurar Selenium con Chrome: from selenium import webdriver driver = webdriver.Chrome()

Paso 2 Navegar a la página que se desea imprimir: driver.get(https://www.selenium.dev)

Paso 3 Configurar las opciones de impresión Selenium ofrece la clase PrintOptions para ajustar la apariencia del PDF. from selenium.webdriver.common.print_page_options import PrintOptions print_options = PrintOptions() print_options.orientation = portrait print_options.scale = 0.60 print_options.background = True

Paso 4 Generar el PDF Al invocar driver.print_page(print_options = print_options) Selenium devuelve el PDF como una cadena en base64. Hay que decodificar esa cadena a bytes para obtener un archivo PDF válido. import base64 pdf_base64 = driver.print_page(print_options = print_options) pdf_bytes = base64.b64decode(pdf_base64)

Paso 5 Guardar el PDF en disco Abrir el fichero en modo binario es imprescindible para no corromper el documento. with open(website_print.pdf, wb) as f: f.write(pdf_bytes)

Paso 6 Cerrar el navegador Siempre libere recursos con driver.quit()

Consejo práctico Para inspeccionar resultados puede guardar la cadena base64 en un .txt y el resultado decodificado en un .pdf y comparar ambos archivos. with open(output_str.txt, w) as f: f.write(pdf_base64) with open(output_bytes.pdf, wb) as f: f.write(pdf_bytes)

Ejemplo completo resumido import base64 from selenium import webdriver from selenium.webdriver.common.print_page_options import PrintOptions driver = webdriver.Chrome() driver.get(https://www.selenium.dev) print_options = PrintOptions() print_options.orientation = portrait print_options.scale = 0.50 print_options.background = False pdf_base64 = driver.print_page(print_options = print_options) pdf_bytes = base64.b64decode(pdf_base64) with open(website_print.pdf, wb) as f: f.write(pdf_bytes) driver.quit()

Aplicaciones y servicios profesionales En Q2BSTUDIO ofrecemos desarrollo de soluciones que integran automatización web y generación de documentos PDF dentro de flujos empresariales a medida. Somos especialistas en software a medida, aplicaciones a medida y ofrecemos también servicios en inteligencia artificial, ciberseguridad y cloud. Si necesita integrar la generación automática de PDFs en una plataforma, podemos diseñar la solución y desplegarla en entornos seguros y escalables. Conozca nuestras opciones de desarrollo de aplicaciones y software a medida para proyectos que requieren integración con Selenium o procesos automatizados.

Servicios complementarios Q2BSTUDIO no solo desarrolla la parte funcional, también implementa medidas de ciberseguridad y pruebas de pentesting para asegurar la integridad y confidencialidad de los documentos generados. Además ofrecemos servicios cloud aws y azure para desplegar pipelines de generación de informes y servicios inteligencia de negocio con integración de Power BI. Para proyectos que incorporan modelos o agentes IA contamos con experiencia en ia para empresas y agentes IA y podemos integrar capacidades avanzadas de inteligencia artificial para procesado automático de contenido.

Palabras clave y posicionamiento El uso de Selenium para generar PDFs encaja perfectamente en soluciones empresariales que requieren automatización de procesos, integración con servicios cloud aws y azure, o entrega de informes a través de power bi y servicios inteligencia de negocio. Si su organización busca mejorar la eficiencia con aplicaciones a medida y soluciones de inteligencia artificial y ciberseguridad, en Q2BSTUDIO diseñamos e implementamos la solución completa. Consulte nuestros servicios de inteligencia artificial para empresas para explorar opciones de automatización avanzada y agentes IA.

Resumen final Imprimir páginas web a PDF con Selenium y Python es directo: configurar el driver, ajustar PrintOptions, decodificar el base64 y guardar en modo binario. Para proyectos de mayor envergadura, integración con business intelligence o despliegue seguro en la nube, Q2BSTUDIO aporta experiencia en software a medida, aplicaciones a medida, inteligencia artificial, ciberseguridad y servicios cloud para llevar su proyecto de prueba de concepto a producción.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat