【问题标题】:Extract text from HTML with beautifulSoup使用 beautifulSoup 从 HTML 中提取文本
【发布时间】:2018-09-12 10:58:55
【问题描述】:

我正在尝试用漂亮的汤 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()

如何分别获取字符串 Film、Location 和 Phone 的值?

【问题讨论】:

    标签: python beautifulsoup html-parsing


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多