Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Huge code problems (buttons(PyQt5),PyQt5 Threads, Windows etc)
#1
Button reacts like it's pressed... but window's not opened...

New window (with that button) won't open after function (in a Thread Class)...

See more about that down below:

I have a function eBaySearch in the Thread class, which needs to be called when the button is clicked. The thing is that I want to run that function, scrape some information while there is a window on the screen saying (for example) "Your search is in progress...". When the function ends, that window ("Your search is in progress...") needs to close and one new window should be opened. What's the problem ? Well I have a lot of problems in here, code is a mess because I am 15 y.o beginner who worked more in Cpp than in any other language but ok.

First, I can't use threads, probably I don't understand them the right way, so if you can somehow fix this to do what I said (or somewhere near that), it would be really, really good. I don't have much time and I am struggling for some days.

Second, when function ends, the "Your search is in progress..." window closes, but then application stops, doesn't show anything more, doesn't react...

Also, third, I had a problem that it won't open new window, it presses the button that is on that window that should be loaded, and then crashes the application.

What a mess, right ?

Also, I tried creating object without "self" in a class, I tried opening new window in various different places, with and without "self", I am now currently using "bool" to check has search ended but for some reason that doesn't work too.... It worked before like when it sets isEBAYFinished to false, it would print the message in that if statement and even close the window, but won't open the new one.

Well, here's my code that can probably help you out (sorry, I know, it's a mess, but please I don't have much time, so if it's solvable and you can solve it please help me out):
class Window_FinishedNotification_EBAY(QWidget):
    def __init__(self, parent=None):
        super(Window_FinishedNotification_EBAY, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("WebScraper v1.0 - Luka N.")
        self.layout = QGridLayout()
        label1 = QLabel(self)
        buttonNext = QPushButton(self)
        newfont = QtGui.QFont("Arial", 10, QtGui.QFont.Bold)
        label1.setFont(newfont)
        label1.setText("Your search has been finished! Press Next to continue")
        label1.setAlignment(Qt.AlignHCenter)
        buttonNext.setText("Next")
        self.layout.addWidget(label1, 0, 0, 1, 4)
        self.layout.addWidget(buttonNext,1,4,1,1)

        buttonNext.clicked.connect(self.buttonNext_clicked())
        self.setLayout(self.layout)
        self.show()

    def thisButton_сlicked(self):
        print("Jel ovo nesto ?")
        pass

class Window_FinishedNotification_EBAY2(QWidget):
    def __init__(self, parent=None):
        super(Window_FinishedNotification_EBAY2, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("WebScraper v1.0 - Luka N.")
        self.layout = QGridLayout()
        label1 = QLabel(self)
        newfont = QtGui.QFont("Arial", 10, QtGui.QFont.Bold)
        label1.setFont(newfont)
        label1.setText("Search in progress...")
        label1.setAlignment(Qt.AlignHCenter)

        self.layout.addWidget(label1, 0, 0, 1, 4)

        #buttonNext.clicked.connect(self.buttonNext_clicked())
        self.setLayout(self.layout)
        self.show()

class Window_eBay_Search(QDialog):
    def __init__(self, parent=None):
        super(Window_eBay_Search, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        lineEdit = QLineEdit(self)
        self.setWindowTitle("WebScraper v1.0 - Luka N.")
        self.layout = QGridLayout()
        label1 = QLabel(self)
        buttonNext = QPushButton(self)
        #label2 = QLabel(self)
        label1.setText("Input an article:")
        buttonNext.setText("Next")
        newfont = QtGui.QFont("Arial", 10, QtGui.QFont.Bold)
        label1.setFont(newfont)
        #label2.setFont(newfont)
        #label2.setStyleSheet("color: red")
        self.layout.addWidget(label1,0,0,1,4)
        self.layout.addWidget(lineEdit,0,4,1,50)
        self.layout.addWidget(buttonNext,0,60,1,1)
        self.layout.addWidget(QLabel(""),4,0,0,50)
        buttonNext.clicked.connect(lambda: self.buttonNext_clicked(self.layout, lineEdit.text()))
        self.setLayout(self.layout)
        self.show()

    def buttonNext_clicked(self, layoutPassed, search2):
        if search2 != "":
            search = search2
            global toSearch
            toSearch = search2
            self.get_thread = InProgressThread()
            #self.get_thread.finished.connect(self.done)
            self.get_thread.start()
            self.window_FinishedNotification_EBAY2 = Window_FinishedNotification_EBAY2()
            global isEBAYFinished
            isEBAYFinished = False
            self.window_FinishedNotification_EBAY2.show()
            self.close()
            if isEBAYFinished == True:
                self.window_FinishedNotification_EBAY2.close()
                print("YES")

        else:
            label2 = QLabel(self)
            label2.setFont(QtGui.QFont("Arial", 10, QtGui.QFont.Bold))
            label2.setStyleSheet("color: red")
            label2.setText("You must enter something")
            layoutPassed.addWidget(label2,4,0,1,4)


    def threadDone(self):
        QMessageBox.warning(self,"DONE :D") # Idk what's this I swear


class InProgressThread(QThread):
    add_post = pyqtSignal(str)
    def __init__(self, parent=None):
        super(InProgressThread,self).__init__(parent)

    def eBaySearch(self):
        global toSearch
        search = toSearch
        print("STARTEDDDDD")
        print("SEARCH: " + toSearch)
        file = open("OutputEBAY", "w")
        baseLink = "https://www.ebay.com/sch/i.html?_from=R40&_nkw="
        # startLink = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=Gtx1050&_sacat=0"
        startLink = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw="
        for i in search:
            if i == " ":
                startLink += "+"
                baseLink += "+"
            else:
                startLink += i
                baseLink += i

        startLink += "&_sacat=0"
        baseLink += "&_sacat=0&_pgn="

        counterDict = {}
        maxDict = {}
        compressedDict = {}
        lastSum = 0
        averagePerPage = []
        totalAverage = 0.0
        for x in range(1, 150):

            counter = 0
            sum = 0.0
            if x == 1:
                generatedLink = startLink
            else:
                generatedLink = baseLink + str(x)

            page = requests.get(generatedLink)
            contents = page.text
            soup = BeautifulSoup(contents, "html.parser")
            mainContentPrice = soup.find_all('span', class_="s-item__price")
            mainContentPlaces = soup.find_all('span', class_=["s-item__location", "s-item__itemLocation"])
            print(generatedLink)
            for i, j in zip(mainContentPrice, mainContentPlaces):
                file.write("UNSLICED:" + str(i.text) + "\n")
                indexT = (i.text).find("t")
                indexComma = (i.text).find(",")

                if indexT != -1:  # There is 't' which represent existence 'to'
                    firstPriceCut = (i.text)[indexT + 3:]
                    indexComma = firstPriceCut.find(",")  # We need to check if there is comma in
                    if indexComma != -1:  # There is comma, which means the price is over $999
                        beforeComma = float(firstPriceCut[1:indexComma]) * 1000
                        afterComma = float(firstPriceCut[indexComma + 1:])
                        price = beforeComma + afterComma

                    else:  # There is no comma, which means the price is less than $1000
                        price = float(firstPriceCut[1:])


                else:  # There is no 't', so there is only one price

                    if indexComma != -1:  # There is comma, which means the price is over $999
                        beforeComma = float((i.text)[1:indexComma]) * 1000
                        afterComma = float((i.text)[indexComma + 1:])
                        price = beforeComma + afterComma

                    else:  # There is no comma, which means the price is less than $1000
                        price = float((i.text)[1:])

                file.write(str(counter) + "SLICED: " + str(price) + "\n")
                sum += price
                counter += 1
                # Adding places and prices to dictionary
                for x in mainContentPlaces:
                    if x.text in compressedDict:
                        compressedDict[x.text] += price
                        counterDict[x.text] += 1

                        if maxDict[x.text] < price:
                            maxDict[x.text] = price

                    else:
                        compressedDict[x.text] = 1
                        counterDict[x.text] = 1
                        maxDict[x.text] = -1

            if sum == lastSum:
                print("SUMAAAA")
                print("LASTSUM:", lastSum)
                break

            if counter > 0:
                averagePerPage.append(sum / counter)
                # totalAverage += sum/counter
                file.write("TOTAL AVERAGE: " + str(totalAverage) + "\n")
                print("SUMA:", sum)
                print("LASTSUM:", lastSum)

            else:
                print("KRAJ2")
                break

            lastSum = sum

        isEBAYFinished = True
        if len(averagePerPage) != 0:
            maxElem = max(i for i in averagePerPage)

            averagePerPage.remove(maxElem)

            for i in averagePerPage:
                totalAverage += i

            print("TOTAL AVERAGE: ${0:.2f}".format(totalAverage / len(averagePerPage)))

            file.write("${0:.2f}".format(totalAverage / len(averagePerPage)))

        else:
            print("Invalid search!")
        isEBAYFinished = True
        window_finishednotification_ebay = Window_FinishedNotification_EBAY()
        window_finishednotification_ebay.show()

        file.close()

    def run(self):
        print("It's here, function's going to be started")
        self.eBaySearch()
        self.add_post.emit("EMITTED")
        print("DONE")
        print("THIS") # I swear I don't understand this "self.add_post.emit("EMITTED" line, I just tried to copy it from the internet but it's impossible to make it work.
(crossposted from StackOverflow)
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  [PyQt] Send data between windows Pyqt5 and Qt Designer kkonrad002 8 215 Sep-05-2019, 02:25 PM
Last Post: Denni
  PyQt5 : Interpreter Crashes While Initializing Message Box iMuny 7 192 Aug-29-2019, 01:38 PM
Last Post: iMuny
  Find active PyQT5 textline and add result to dictionary mart79 3 193 Jul-31-2019, 03:25 PM
Last Post: Denni
  Windows GUI with push buttons to launch python scripts drifterf 7 294 Jul-17-2019, 05:34 PM
Last Post: Yoriz
  PyQT5 : Unable to Create Another Dialog While One is Open iMuny 3 326 Jul-17-2019, 11:40 AM
Last Post: iMuny
  updating to pyqt5 LavaCreeperKing 4 563 Jun-30-2019, 10:13 PM
Last Post: LavaCreeperKing
  pyQt5 QCalendarWidget setHeaderTextFormat zazen000 0 381 Apr-14-2019, 11:50 PM
Last Post: zazen000
  [Pyqt5]Display name of new inserted USB stick on GUI Atalanttore 0 439 Mar-24-2019, 08:29 PM
Last Post: Atalanttore
  Python3/PyQt5/gnuplot on linux erg 1 369 Mar-20-2019, 01:57 PM
Last Post: Axel_Erfurt
  How to show graph as a slideshow in PyQt5 using matplotlib binsha 0 859 Mar-08-2019, 03:58 AM
Last Post: binsha

Forum Jump:


Users browsing this thread: 1 Guest(s)