【问题标题】:Parsing HTML table with beautifulsoup用 beautifulsoup 解析 HTML 表格
【发布时间】:2014-09-03 20:55:48
【问题描述】:

我想得到这样的信息,尤其是strong标签后面的文字,beautifulsoup怎么能做到,谢谢。

<span class=JamalsinRed>H.S. AHMED ALLY</span>              
<hr align="left" width="400" color="#CCCCCC">
<strong>Address : </strong>217/7,Saleh Market,Adamjee Road,Saddar<br>
<strong>City : </strong>Rawalpindi<br>
<strong>Phone # : </strong>(92 51) 5511748, 5125396<br>
<strong>Fax : </strong>(92 51) 5511749<br>
<strong>E-mail : </strong><a class=b href='mailto:hsaforce@cyber.net.pk'>hsaforce@cyber.net.pk</a><br><strong>Web : </strong>
<a target=_blank href='http://www.hsahmedally.com'>www.hsahmedally.com</a><br>

【问题讨论】:

    标签: python html html-parsing beautifulsoup


    【解决方案1】:

    我们的想法是制作一个很好的可重用函数,它将字段名称作为参数并输出字段值。该函数将搜索strong 元素,其中text 以传入的字段名称和get the next sibling 开头:

    from bs4 import BeautifulSoup
    
    data = """
    <div>
        <span class="JamalsinRed">H.S. AHMED ALLY</span>
        <hr align="left" width="400" color="#CCCCCC">
          <strong>Address : </strong>217/7,Saleh Market,Adamjee Road,Saddar<br>
          <strong>City : </strong>Rawalpindi<br>
          <strong>Phone # : </strong>(92 51) 5511748, 5125396<br>
          <strong>Fax : </strong>(92 51) 5511749<br>
          <strong>E-mail : </strong><a class=b href='mailto:hsaforce@cyber.net.pk'>hsaforce@cyber.net.pk</a><br><strong>Web : </strong>
          <a target=_blank href='http://www.hsahmedally.com'>www.hsahmedally.com</a><br>
        </hr>
    </div>
    """
    
    def get_field_value(soup, field):
        return soup.find('strong', text=lambda x: x.startswith(field)).next_sibling
    
    soup = BeautifulSoup(data)
    print get_field_value(soup, 'Address')
    print get_field_value(soup, 'City')
    

    打印:

    217/7,Saleh Market,Adamjee Road,Saddar
    Rawalpindi
    

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 2017-02-15
      • 2012-01-12
      • 1970-01-01
      • 2012-12-13
      相关资源
      最近更新 更多