При нажатии на кнопку программа закрывается и выдаёт ошибку

Я сделал программу для скачивания HTML кода страницы по её url с помощью Python, Wget, PyQt5, Pyside2.

При нажатии на кнопку должен по идее создаваться .html файл с кодом в том месте, откуда была запущена программа, но почему то после нажатия на кнопку он закрывается с сообщением об ошибке:

C:\Users\w\parsersite>python parser.py
Traceback (most recent call last):
  File "parser.py", line 24, in dowload_html
    wget = wget()
UnboundLocalError: local variable 'wget' referenced before assignment

gui.py:

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(450, 314)
        MainWindow.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(133, 203, 219, 255), stop:0.130682 rgba(20, 108, 149, 255), stop:0.323864 rgba(115, 210, 189, 255), stop:0.477273 rgba(90, 205, 117, 255), stop:0.647727 rgba(106, 170, 170, 255), stop:0.835227 rgba(213, 255, 213, 255), stop:1 rgba(128, 255, 151, 255))")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(10, 20, 421, 41))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit.setFont(font)
        self.lineEdit.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(90, 187, 93, 255), stop:0.323864 rgba(97, 230, 162, 255), stop:0.494318 rgba(125, 209, 199, 255), stop:0.630682 rgba(152, 232, 205, 255), stop:0.789773 rgba(172, 221, 200, 255), stop:1 rgba(162, 255, 184, 255));\n"
"border-radius: 20px;")
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(50, 140, 331, 91))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(133, 143, 219, 255), stop:0.130682 rgba(20, 149, 149, 255), stop:0.323864 rgba(84, 210, 182, 255), stop:0.477273 rgba(104, 162, 205, 255), stop:0.647727 rgba(54, 165, 170, 255), stop:0.835227 rgba(154, 170, 255, 255), stop:1 rgba(128, 212, 255, 255));\n"
"border-radius: 15px;")
        self.pushButton.setObjectName("pushButton")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(40, 80, 351, 41))
        self.lineEdit_2.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(90, 187, 93, 255), stop:0.323864 rgba(97, 230, 162, 255), stop:0.494318 rgba(125, 209, 199, 255), stop:0.630682 rgba(152, 232, 205, 255), stop:0.789773 rgba(172, 221, 200, 255), stop:1 rgba(162, 255, 184, 255));\n"
"border-radius: 20px;")
        self.lineEdit_2.setObjectName("lineEdit_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 450, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "СКАЧАТЬ HTML САЙТА"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

parser.py:

from gui import Ui_MainWindow
from PyQt5 import QtWidgets, QtGui, QtCore, uic
from PyQt5.QtGui import QIcon
import sys
import wget
import gui

class Parser(QtWidgets.QMainWindow):
    def __init__(self):
        super(Parser, self).__init__()
        self.parser = Ui_MainWindow()
        self.parser.setupUi(self)
        self.init_UI()

    def init_UI(self):
        self.setWindowTitle('Site Dowloand')
        self.setWindowIcon(QIcon('atom-icon.png'))

        self.parser.lineEdit.setPlaceholderText('Введите url-адрес сайта')
        self.parser.lineEdit_2.setPlaceholderText('Название HTML файла куда будет скачен HTML код страницы')
        self.parser.pushButton.clicked.connect(self.dowload_html)

    def dowload_html(self):
        wget = wget()
        line1 = self.parser.lineEdit.text()
        line2 = self.parser.lineEdit_2.text()
        
        wget.download(line1, line2)

 
app = QtWidgets.QApplication([])
application = Parser()
application.show()
        
sys.exit(app.exec())

Ответы (1 шт):

Автор решения: S. Nick

я не знаком с wget, поэтому предложу вам попробовать, как вариант, простенькое решение вашей задачи с использованием request. Т.к. задача может занять длительное время, она должна выполняться в дополнительном потоке.

import sys
import urllib.request
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout

# from gui import Ui_MainWindow
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(450, 314)
        MainWindow.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(133, 203, 219, 255), stop:0.130682 rgba(20, 108, 149, 255), stop:0.323864 rgba(115, 210, 189, 255), stop:0.477273 rgba(90, 205, 117, 255), stop:0.647727 rgba(106, 170, 170, 255), stop:0.835227 rgba(213, 255, 213, 255), stop:1 rgba(128, 255, 151, 255))")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(10, 20, 421, 41))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.lineEdit.setFont(font)
        self.lineEdit.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(90, 187, 93, 255), stop:0.323864 rgba(97, 230, 162, 255), stop:0.494318 rgba(125, 209, 199, 255), stop:0.630682 rgba(152, 232, 205, 255), stop:0.789773 rgba(172, 221, 200, 255), stop:1 rgba(162, 255, 184, 255));\n"
"border-radius: 20px;")
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(50, 140, 331, 91))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(133, 143, 219, 255), stop:0.130682 rgba(20, 149, 149, 255), stop:0.323864 rgba(84, 210, 182, 255), stop:0.477273 rgba(104, 162, 205, 255), stop:0.647727 rgba(54, 165, 170, 255), stop:0.835227 rgba(154, 170, 255, 255), stop:1 rgba(128, 212, 255, 255));\n"
"border-radius: 15px;")
        self.pushButton.setObjectName("pushButton")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(40, 80, 351, 41))
        self.lineEdit_2.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(90, 187, 93, 255), stop:0.323864 rgba(97, 230, 162, 255), stop:0.494318 rgba(125, 209, 199, 255), stop:0.630682 rgba(152, 232, 205, 255), stop:0.789773 rgba(172, 221, 200, 255), stop:1 rgba(162, 255, 184, 255));\n"
"border-radius: 20px;")
        self.lineEdit_2.setObjectName("lineEdit_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 450, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "СКАЧАТЬ HTML САЙТА"))
       

class CrawlThread(QThread):
    status_signal = pyqtSignal(str)

    def __init__(self):
        super(CrawlThread, self).__init__()
        self.url = ''
        self.fileName = ''

    def run(self):
        self.status_signal.emit('Crawling')
        response = urllib.request.urlopen(self.url)
        self.status_signal.emit('Saving')
        with open(self.fileName, 'w') as f:  
            f.write(response.read().decode('utf-8'))
        self.status_signal.emit('Done')
        

class Parser(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):        
        super().__init__()
        self.setupUi(self)        
        self.setWindowTitle('Site Dowloand')
        self.setWindowIcon(QtGui.QIcon('atom-icon.png'))
        
        self.lineEdit.setPlaceholderText('Введите url-адрес сайта')
        self.lineEdit.setText('https://ru.stackoverflow.com/questions/1237787')
        
        self.lineEdit_2.setPlaceholderText(
            'Название HTML файла куда будет скачен HTML код страницы')
        self.lineEdit_2.setText('q1237787.html')   
        
        self.pushButton.clicked.connect(self.dowload_html)        

        self.crawl_thread = CrawlThread()
        self.crawl_thread.status_signal.connect(self.status_func)
        self.msgBox = None

    def dowload_html(self):
        if not self.lineEdit.text() or not self.lineEdit_2.text():
            msg = QtWidgets.QMessageBox.information(
                self, 
                "Внимание!", 
                f"Введите url и fileName"
            )            
            return
        self.crawl_thread.url = self.lineEdit.text()
        self.crawl_thread.fileName = self.lineEdit_2.text()
        
        self.crawl_thread.start() 

    def status_func(self, status):
        if self.msgBox:
            self.msgBox.hide()
            
        self.msgBox = QtWidgets.QMessageBox()
        self.msgBox.setIcon(QtWidgets.QMessageBox.Information)
        self.msgBox.setWindowTitle("Status!")
        self.msgBox.setText(f"{status}")
        self.msgBox.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Parser()
    w.show()
    sys.exit(app.exec_())

введите сюда описание изображения

→ Ссылка