How can I narrow down my soup.find search to one line in the HTML

Viewed 63

I'm trying to scrape one line of html from this:

<strong class="listingPrice">
    £75- £85
    <abbr title="">pw</abbr>
</strong>

The line I'm trying to scrape is "£75- £85"

My current code to scrape the page is:

html_text = requests.get("web address").text

soup = BeautifulSoup(html_text, 'lxml')
prices = soup.find_all('strong', class_='listingPrice')

Any advice?

1 Answers

You can use .contents[0]:

from bs4 import BeautifulSoup


doc = """<strong class="listingPrice">
    £75- £85
    <abbr title="">pw</abbr>
</strong>"""

soup = BeautifulSoup(doc, "lxml")

price = soup.select_one(".listingPrice").contents[0].strip()
print(price)

Prints:

£75- £85

Or .find_next() with text=True:

price = soup.select_one(".listingPrice").find_next(text=True).strip()
Related