Python Forum
For Loop Returning 3 Results When There Should Be 1
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For Loop Returning 3 Results When There Should Be 1
#6
You are doing something similar to this:
soup = {'A':1, 'B':2, 'C':3}
class_ = 'B'
for item in soup:
    mt2 = soup.get(class_)
    if mt2:
        print(mt2)
    else:
        print('There is no record')
Output:
2 2 2
In this example and yours you will get a different item each time you iterate through soup, but soup either contains "class_" or not, and that is independent of the current item.

How you fix this depends on what you want to get from soup. From your description I think you would find all span and iterate through those items, comparing the item's class against your pattern. Something like this:
from bs4 import BeautifulSoup
 
with open("out_of_stock2.html", encoding="utf8") as fp:
    soup = BeautifulSoup(fp, 'html.parser')
    for item in soup.find('span'):
        if item['class_'] == "w_A w_C w_B mr1 mt1 ph1":
            print(item)
        else:
            print ('No match')
knight2000 likes this post
Reply


Messages In This Thread
RE: For Loop Returning 3 Results When There Should Be 1 - by deanhystad - Sep-26-2021, 07:41 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  WHILE LOOP NOT RETURNING USER INPUT AFTER ZerroDivisionError! HELP! ayodele_martins1 7 1,087 Oct-01-2023, 07:36 PM
Last Post: ayodele_martins1
  Help add for loop results in a list paulo79 4 1,587 Mar-09-2022, 05:49 PM
Last Post: deanhystad
  returning values in for loop Nickd12 4 12,359 Dec-17-2020, 03:51 AM
Last Post: snippsat
  Search Results Web results Printing the number of days in a given month and year afefDXCTN 1 2,255 Aug-21-2020, 12:20 PM
Last Post: DeaD_EyE
  Adding loop results as rows in dataframe Shreya10o 2 2,214 May-09-2020, 11:00 AM
Last Post: Shreya10o
  How to append one function1 results to function2 results SriRajesh 5 3,196 Jan-02-2020, 12:11 PM
Last Post: Killertjuh
  Returning true or false in a for loop bbop1232012 3 8,184 Nov-22-2018, 04:44 PM
Last Post: bbop1232012
  RegExp: returning 2nd loop in new document syoung 5 3,915 May-02-2018, 12:36 PM
Last Post: syoung

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020