Daniel
Daniel

Reputation: 191

Find only one element in html page using soup

Is it possible to find with soup just one element in an html page or it's designed to always look for all the elements with same attributes? I have this code below and again I'm choosing ebay because it's handy. I just want to print the first price on the page displayed as an integer in the console. I only get None responses. I tried all the combinations possible for the find function with soup.

import requests
from bs4 import BeautifulSoup
import lxml


url = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1312&_nkw=Ryzen+9+3950x&_sacat=0"

page = requests.get(url)
soup = BeautifulSoup(page.content, "lxml")
page.close()

price = soup.find("div",href_="https://www.ebay.com/p/10035392721?iid=313304858607#UserReviews", class_= "s-item__price").get_text(strip=True)

print(price)

Please show me how do I print one price with soup. Thank you.

Upvotes: 1

Views: 63

Answers (1)

MendelG
MendelG

Reputation: 20098

To get the first price, see the following example using a CSS Selector:

import requests
from bs4 import BeautifulSoup


url = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1312&_nkw=Ryzen+9+3950x&_sacat=0"

soup = BeautifulSoup(requests.get(url).content, "lxml")

print(soup.select_one("li:nth-of-type(n+2) span.s-item__price").text)

Output:

$575.00

To get all tags use:

for tag in soup.select("li:nth-of-type(n+2) span.s-item__price"):
    print(tag.text)

Upvotes: 1

Related Questions