Anoop Krishnan
Anoop Krishnan

Reputation: 331

Extract text from HTML with beautifulSoup

I am trying to parse an html with beautiful soup 4 but unable to get the data

<div class="inside">
<a href="http://www.linkar.com">
  <b>A Show</b><br/>
  <img alt="A Show" height="83" src="http://www.linkar.com/679.jpg"/>
</a>
<br/>Film : Gladiator
<br/>Location : example street, London, UK
<br/>Phone : +83817447184<br/>
</div>

I am able to get the string "A Show" by using

soup = BeautifulSoup(html, "html.parser")
a_show = soup.find('b').get_text()

How can I get values of strings Film, Location and Phone seperately?

Upvotes: 0

Views: 2040

Answers (1)

Rakesh
Rakesh

Reputation: 82755

You can use BS with re.

Ex:

from bs4 import BeautifulSoup
import re


html = """<div class="inside">
<a href="http://www.linkar.com">
  <b>A Show</b><br/>
  <img alt="A Show" height="83" src="http://www.linkar.com/679.jpg"/>
</a>
<br/>Film : Gladiator
<br/>Location : example street, London, UK
<br/>Phone : +83817447184<br/>
</div>"""

soup = BeautifulSoup(html, "html.parser")
a_show = soup.find('div', class_="inside").text
film = re.search("Film :(.*)", a_show)
if film:
    print(film.group())

location = re.search("Location :(.*)", a_show)
if location:
    print(location.group())

phone = re.search("Phone :(.*)", a_show)
if phone:
    print(phone.group())

Output:

Film : Gladiator
Location : example street, London, UK
Phone : +83817447184

or

content = re.findall("(Film|Location|Phone) :(.*)", a_show)
if content:
    print(content)
# --> [(u'Film', u' Gladiator'), (u'Location', u' example street, London, UK'), (u'Phone', u' +83817447184')]

Upvotes: 4

Related Questions