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] Cannot get PyQt5 to import DoDods 2 70 Apr-03-2020, 08:57 AM
Last Post: DoDods
  Need code for buttons to move to previous and next documents JayCee 0 144 Apr-02-2020, 05:19 PM
Last Post: JayCee
  PyQt5: Iterate through rows to check for a value keegan_010 2 110 Mar-23-2020, 11:30 PM
Last Post: keegan_010
  PyQt5 Help - Absolute Beginner! mnash48 2 170 Mar-20-2020, 11:51 PM
Last Post: deanhystad
  [PyQt] Python PyQt5 - Change label text dynamically based on user Input ppel123 1 133 Mar-20-2020, 07:21 AM
Last Post: deanhystad
  A Simple PyQt5 Class zoro 15 1,067 Mar-02-2020, 07:25 PM
Last Post: micseydel
  PyQt5 Installation Clamantium 2 731 Feb-07-2020, 09:19 PM
Last Post: snippsat
  [PyQt] how to transform pyqt4 code to pyqt5 code atlass218 4 186 Jan-20-2020, 05:45 PM
Last Post: Axel_Erfurt
  plotting 2d and 3d using pyqt5 and pyqtgraph and GLSurfacePlotItem kiyoshi7 1 936 Jan-20-2020, 12:13 AM
Last Post: kiyoshi7
  PyQt5 How do you make a functioning login and registration program? YoshikageKira 4 752 Jan-17-2020, 09:51 PM
Last Post: pavulon

Forum Jump:


Users browsing this thread: 1 Guest(s)