Extracting text with Beautiful Soup under font size

Viewed 322

I recently started learning python and i want to extract text from a page under

<p>
<font size="">
some text</font>
</p>

but cant get the text inside font size Any solution?

Edit: The "some text" changes on refresh that's the problem

4 Answers

Try this,

from bs4 import BeautifulSoup

text = """<p>
<font size="10">
some text</font>
</p>"""

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

soup.find("font").text        # some text
soup.find("font").get('size') # 10
from bs4 import BeautifulSoup as bs

b = bs("<p>\
<font size="5">\
some text</font>\
</p>")

b.find("font").attrs["size"]

This works on you specific example, but may need tailoring depending on the real html you need to parse:

from bs4 import BeautifulSoup

html="""<p>
<font size="">
some text</font>
</p>"""

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

print(soup.find('p').text)

I think you can do something like this!

import bs4
import re

data = """
<p>
<font size="">some text</font>
</p>
"""
def striphtml(data):
    p = re.compile(r'<.*?>')
    return p.sub('', data)

bs = bs4.BeautifulSoup(data, "html.parser")
text = bs.find_all('font')
print(striphtml(str(text)))

Output : [some text]

Related