Home > Mobile >  Getting multiple lists when I only want the last one
Getting multiple lists when I only want the last one

Time:07-23

#My Code:

url = 'http://wholepeople.com/best-thrift-stores-in-nyc/#:~:text=1 Beacon's Closet. We think any thrifter in,... 10 Emma Rogue. ... More items... '
page = urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
h2Tags = soup.find_all('h2')
for store in h2Tags[:12]:
    allStores = (store.text)
    storeList.append(allStores)
    print(storeList)

#What I'm getting:

['Beacon’s Closet']
['Beacon’s Closet', 'Laced Up']
['Beacon’s Closet', 'Laced Up', '2ND Street']
['Beacon’s Closet', 'Laced Up', '2ND Street', 'Buffalo Exchange']
['Beacon’s Closet', 'Laced Up', '2ND Street', 'Buffalo Exchange', 'Tired Thrift']
['Beacon’s Closet', 'Laced Up', '2ND Street', 'Buffalo Exchange', 'Tired Thrift', 'L Train Vintage']
['Beacon’s Closet', 'Laced Up', '2ND Street', 'Buffalo Exchange', 'Tired Thrift', 'L Train Vintage', 'Cure Thrift Shop']
['Beacon’s Closet', 'Laced Up', '2ND Street', 'Buffalo Exchange', 'Tired Thrift', 'L Train Vintage', 'Cure Thrift Shop', 'Crossroads Trading']
['Beacon’s Closet', 'Laced Up', '2ND Street', 'Buffalo Exchange', 'Tired Thrift', 'L Train Vintage', 'Cure Thrift Shop', 'Crossroads Trading', 'The Attic']
['Beacon’s Closet', 'Laced Up', '2ND Street', 'Buffalo Exchange', 'Tired Thrift', 'L Train Vintage', 'Cure Thrift Shop', 'Crossroads Trading', 'The Attic', 'Emma Rogue']
['Beacon’s Closet', 'Laced Up', '2ND Street', 'Buffalo Exchange', 'Tired Thrift', 'L Train Vintage', 'Cure Thrift Shop', 'Crossroads Trading', 'The Attic', 'Emma Rogue', 'Flamingo’s Vintage Pound']
['Beacon’s Closet', 'Laced Up', '2ND Street', 'Buffalo Exchange', 'Tired Thrift', 'L Train Vintage', 'Cure Thrift Shop', 'Crossroads Trading', 'The Attic', 'Emma Rogue', 'Flamingo’s Vintage Pound', 'Monk Vintage Clothing']

#I only need the last list and don't know why/how I got what I did

CodePudding user response:

Try this to get the last list:

url = 'http://wholepeople.com/best-thrift-stores-in-nyc/#:~:text=1 Beacon's Closet. We think any thrifter in,... 10 Emma Rogue. ... More items... '
page = urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
h2Tags = soup.find_all('h2')
for store in h2Tags[:12]:
    allStores = (store.text)
    storeList.append(allStores)
print(storeList)

You are printing the list every time, and you only want to print it after the list has been generated. So, just move the print statement outside of the loop.

  • Related