Search code examples
pythonlistweb-scraping

How to assign numbers to a list of returned python data that I can call on to print


Total noob here. I have searched online and cant find the answer to what i'm trying to do. my code here:

import bs4 as bs
import urllib.request

sauce = urllib.request.urlopen('https://www.amazon.com/gp/rss/
bestsellers/kitchen/289851/ref=zg_bs_289851_rsslink').read()

soup = bs.BeautifulSoup(sauce,'lxml')

for title in soup.find_all('title'):

    output = title.string

    print(output)

gives me this output:

Amazon.com: Best Sellers in Kitchen & Dining > Kitchen Knives & Cutlery 
Accessories
#1: Kitchen Knife Sharpener - 3-Stage Knife Sharpening Tool Helps Repair, 
Restore and Polish Blades - Cut-Resistant Glove Included (Black)
#2: KitchenIQ 50009 Edge Grip 2 Stage Knife Sharpener, Black
#3: Bavarian Edge Kitchen Knife Sharpener by BulbHead, Sharpens, Hones, & 
Polishes Serrated, Beveled, Standard Blades
#4: PriorityChef Knife Sharpener for Straight and Serrated Knives, 2-Stage 
Diamond Coated Wheel System, Sharpens Dull Knives Quickly, Safe and Easy to 
Use
#5: MAIRICO Ultra Sharp Premium Heavy Duty Kitchen Shears and Multi Purpose 
Scissors
#6: OXO Good Grips 3-in-1 Avocado Slicer, Green
#7: LINKYO Electric Knife Sharpener, Kitchen Knives Sharpening System
#8: BambooWorx Sushi Making Kit – Includes 2 Sushi Rolling Mats, Rice 
Paddle, Rice Spreader |100% Bamboo Sushi Mats and Utensils.
#9: HOMWE Kitchen Cutting Board (3-Piece Set) | Juice Grooves w/ Easy-Grip 
Handles | BPA-Free, Non-Porous, Dishwasher Safe | Multiple Sizes (Set of 
Three, Gray)
#10: Ouddy 16 Inch Magnetic Knife Holder, Stainless Steel Magnetic Knife 
Bar, Magnetic Knife Strip, Knife Rack Strip

And what I'm trying to do is save each item number into a list, that I can call on...for example print item 1, or item 2 or etc. where it would only print the specific line.

Thank you very much in advance for any help.


Solution

  • A quick solution could be to do something like the following

    import bs4 as bs
    import urllib.request
    
    sauce = urllib.request.urlopen('https://www.amazon.com/gp/rss/bestsellers/kitchen/289851/ref=zg_bs_289851_rsslink').read()
    
    soup = bs.BeautifulSoup(sauce,'lxml')
    
    output_list = list()
    
    for title in soup.find_all('title'):
    
        output = title.string
        output_list.append(output)
    

    Now every result is in a list like you wanted.

    Because of the title taking index 0, you can print your results for each number by simply doing:

    print(output_list[1]) # Print the first item
    print(output_list[2]) # Print the second item
    

    To get them all, line by line, something like the following would work:

    for i in range(1, len(output_list)):
        print(output_list[i])
    

    Hope this helps.