Cómo montar un navegador web simple con Qt. El framework se encarga del trabajo duro: acceder al URL especificado, cargar los recursos y renderizar el contenido con WebKit, librería detrás de Safari y Chrome, haciendo uso de la clase QWebView.
Para el código adaptado a PyQt 5 véase Navegador web simple con PyQt5.
Descargar códigos de fuente como ZIP
Ambos ejemplos utilizan layouts para modificar el tamaño del control automáticamente.
1
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# simpleweb.py
#
# Copyright 2013 Recursos Python - www.recursospython.com
#
#
import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QMetaObject, QUrl
from PyQt4.QtGui import QHBoxLayout, QMainWindow, QWidget
from PyQt4.QtWebKit import QWebView
class Widgets(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle("Simple Web Browser")
self.widget = QWidget(self)
self.webview = QWebView()
self.webview.load(QUrl("https://www.recursospython.com/"))
self.layout = QHBoxLayout()
self.layout.addWidget(self.webview)
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
QMetaObject.connectSlotsByName(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Widgets()
window.show()
sys.exit(app.exec_())
2
Además del control QWebView, añade una barra de direcciones y botones de ir hacia atrás, hacia adelante y actualizar.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# simplewebx.py
#
# Copyright 2013 Recursos Python - www.recursospython.com
#
#
import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QMetaObject, QUrl
from PyQt4.QtGui import (QHBoxLayout, QLineEdit, QMainWindow,
QPushButton, QVBoxLayout, QWidget)
from PyQt4.QtWebKit import QWebView
class Widgets(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle("Simple Web Browser")
self.widget = QWidget(self)
# Widget para el navegador
self.webview = QWebView()
self.webview.load(QUrl("https://www.recursospython.com/"))
self.webview.urlChanged.connect(self.url_changed)
# Ir hacia atrás
self.back_button = QPushButton("<")
self.back_button.clicked.connect(self.webview.back)
# Ir hacia adelante
self.forward_button = QPushButton(">")
self.forward_button.clicked.connect(self.webview.forward)
# Actualizar la página
self.refresh_button = QPushButton("Actualizar")
self.refresh_button.clicked.connect(self.webview.reload)
# Barra de direcciones
self.url_text = QLineEdit()
# Cargar la página actual
self.go_button = QPushButton("Ir")
self.go_button.clicked.connect(self.url_set)
self.toplayout = QHBoxLayout()
self.toplayout.addWidget(self.back_button)
self.toplayout.addWidget(self.forward_button)
self.toplayout.addWidget(self.refresh_button)
self.toplayout.addWidget(self.url_text)
self.toplayout.addWidget(self.go_button)
self.layout = QVBoxLayout()
self.layout.addLayout(self.toplayout)
self.layout.addWidget(self.webview)
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
QMetaObject.connectSlotsByName(self)
def url_changed(self, url):
"""Actualizar la barra de direcciones"""
self.url_text.setText(url.toString())
def url_set(self):
"""Acceder a un nuevo URL"""
self.webview.setUrl(QUrl(self.url_text.text()))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Widgets()
window.show()
sys.exit(app.exec_())
Vista previa
Curso online 👨💻
¡Ya lanzamos el curso oficial de Recursos Python en Udemy!
Un curso moderno para aprender Python desde cero con programación orientada a objetos, SQL y tkinter en 2024.
Consultoría 💡
Ofrecemos servicios profesionales de desarrollo y capacitación en Python a personas y empresas. Consultanos por tu proyecto.

konniskatt says:
Hola! Como haría para que esto me funcione en PyQt5?
Muchas gracias.
Recursos Python says:
Hola, acá tenés el código adaptado a PyQt5: recursospython.com/codigos-de-fuente/navegador-web-simple-con-pyqt-5/.
Saludos
Fancisco Ameri says:
Hola, me podrias enviar por mail el codigo por que me salta que hay un error de tabulacion
Recursos Python says:
El problema radica en el plug-in para el resaltado de sintaxis del código, que al copiarlo suprime los espacios. Te he enviado el archivo, de todas maneras la descarga funciona perfectamente.
Saludos.