用beautifulSoup从HTML中提取文本

2024-06-16 11:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用漂亮的soup4解析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>

我可以使用

^{pr2}$

如何分别获取字符串电影、位置和电话的值?在


Tags: 数据brdivcomhttpimghtmlwww
1条回答
网友
1楼 · 发布于 2024-06-16 11:19:32

您可以将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())

输出:

^{pr2}$

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')]

相关问题 更多 >