使用beautifulSoup从HTML中提取文本

问题描述 投票:0回答:1

我试图解析一个美丽的汤4的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>

我可以通过使用获得字符串“A Show”

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

如何分别获得字符串,位置和电话的值?

python beautifulsoup html-parsing
1个回答
4
投票

你可以使用BSre

例如:

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())

输出:

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

要么

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')]
© www.soinside.com 2019 - 2024. All rights reserved.