Home > database >  How Can I Assign A Variable To All Of The Items In A List?
How Can I Assign A Variable To All Of The Items In A List?

Time:08-06

I'm following a guide and it's saying to print the first item from an html document that contains the dollar sign.

It seems to do it correctly, outputting a price to the terminal and it actually being present on the webpage. However, I don't want to have just that single listing, I want to have all of the listings and print them to the terminal.

I'm almost positive that you could do this with a for loop, but I don't know how to set that up correctly. Here's the code I have so far with a comment on line 14, and the code I'm asking about on line 15.

from bs4 import BeautifulSoup
import requests
import os

os.system("clear")

url = 'https://www.newegg.com/p/pl?d=RTX 3080'

result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")

prices = doc.find_all(text="$")

#Print all prices instead of just the specified number?
parent = prices[0].parent


strong = parent.find("strong")
print(strong.string)

CodePudding user response:

You could try the following:

from bs4 import BeautifulSoup
import requests
import os

os.system("clear")

url = 'https://www.newegg.com/p/pl?d=RTX 3080'

result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")

prices = doc.find_all(text="$")

for price in prices:
    parent = price.parent
    strong = parent.find("strong")
    print(strong.string)
  • Related