Meera
Meera

Reputation: 21

Extracting span tags using Beautifulsoup

I am trying to extract span tags using beautifulsoup, the code is giving no output

soup = BeautifulSoup(html, "html.parser")
tags  = soup("span")
for tag in tags:
  print(tag)

tag:<tr><td>Romina</td><td><span class="comments">97</span></td></tr>

please help me!! Thank you

Upvotes: 0

Views: 93

Answers (1)

CodeMonkey
CodeMonkey

Reputation: 23748

You need to call find() or find_all() functions with the target tag as the argument, optionally with other constraints (e.g. class name or id) to filter the HTML elements. For more info see docs.

Try this:

from bs4 import BeautifulSoup

html = '''
<table>
<tr><td>Romina</td><td><span class="comments">97</span></td></tr>
</table>
'''

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

for elt in soup.find_all("span", class_="comments"):
    print(elt.text)

Output:

97

If want to store the elements in a list can use list comprehension.

data = [elt.text for elt in soup.find_all("span", class_="comments")]

Upvotes: 2

Related Questions