Home > Enterprise >  How to just get the content of the tag when you use findAll in Beautiful Soup?
How to just get the content of the tag when you use findAll in Beautiful Soup?

Time:06-17

So on the project I'm building I want to find the price contained on the multiple results I got with the findAll() command. Here's the code:

soup = BeautifulSoup(driver.page_source, 'html.parser') 
price = soup.find_all(class_='search-result__market-price--value')
print(price)

And this is what I get:

[<span  tabindex="-1"> $0.11 </span>, <span  tabindex="-1"> $0.24 </span>, ... ]

I tried using this code I found somewhere else price = soup.find_all(class_='search-result__market-price--value')[0].string but it just gave the error IndexError: list index out of range.

What can I do to just get the numbers?

CodePudding user response:

Iterate the ResultSet created by find_all():

soup = BeautifulSoup(driver.page_source, 'html.parser') 
for price in soup.find_all(class_='search-result__market-price--value'):
    print(price.text)

or to just get the numbers

    print(price.text.split('$')[-1])
Example
from bs4 import BeautifulSoup

html='''
<span  tabindex="-1"> $0.11 </span>
<span  tabindex="-1"> $0.24 </span>
'''

soup = BeautifulSoup(html, 'html.parser')

for tag in soup.find_all('span'):
    print(tag.text.split('$')[-1])
Output
0.11 
0.24 
  • Related