Search code examples
pythondeque

Python - deq function prints out 8 times - prevent to print only once?


So I have played abit with deq and almost come up to the finish but there was on concerned that it is printing 8 times due to the length of the deq while I just want it to print out once.

What I have done is:

old_list = []
deq = deque(old_list, maxlen=8)
url = 'https://www.supremecommunity.com/restocks/eu/'

while True:
    try:
        new_list = []

        bs4 = soup(requests.get(url).text, "html.parser")

        for item in bs4.findAll('div', {'class': 'restock-item'}):
            if item.find('div', {'class': 'user-detail'}):
                name = item.find('h5', {'class': 'handle restock-name'}).string
                color = item.find('h6', {'class': 'restock-colorway'}).string

                new_list.append(name + color)

        for newitem in new_list:
            if newitem not in deq:
                print(name)
                print(color)
                deq.append(newitem)

            else:
                print('Sleeping 5 sec')
                time.sleep(5)
    except:
        continue 

Basically it checks the website and prints out name and color and then add it to the list of deq. However my output prints out 8 times of the same name and color because of the maxlen=8 and my question is:

How can I make it so it prints out only once?


Solution

  • You are always printing the same variables name and color as they where lastly defined in the for-loop above.

          name = item.find('h5', {'class': 'handle restock-name'}).string
          color = item.find('h6', {'class': 'restock-colorway'}).string
    

    As you are printing print(name) and print(color) in your second for-loop it always refers to the last values that name and color had.

    To solve this you should refer to the variable newitem in your printing statements.

    EDIT:

    Here you are just concatenating the two strings.

    new_list.append(name + color)
    

    I suggest that you make it a list of lists.

    new_list.append([name,color])
    

    You can then use print(newitem[0]) and print(newitem[1]) to print the different names and colors.