【问题标题】:How to scrape the height and width of a table using Beautifulsoup?如何使用 Beautifulsoup 刮取表格的高度和宽度?
【发布时间】:2011-02-10 13:15:28
【问题描述】:
<table id="t_id" cellspacing="0" border="0" align="center" height="700" width="600" cellpadding="0">
<tbody>
<tr><td> ..test... </td></tr>
<tr><td> ..test... </td></tr>
<tr><td> ..test... </td></tr>
</tbody>
</table>

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    现在人们更喜欢 lxml 而不是 BeautifulSoup。看看这有多简单:

    from lxml import etree
    data = """<table id="t_id" cellspacing="0" border="0" align="center" height="700" width="600" cellpadding="0">
    <tbody>
    <tr><td> ..test... </td></tr>
    <tr><td> ..test... </td></tr>
    <tr><td> ..test... </td></tr>
    </tbody>
    </table>
    """
    tree = etree.fromstring(data)
    table_element = tree.xpath("/table")[0] # because it returns a list of table elements
    print table_element.attrib['height'] + " and " + table_element.attrib['width']
    

    【讨论】:

    • 为什么人们更喜欢lxml?性能原因?因为 BeautifulSoup 解决方案更短,而且看起来更像 pythonic 恕我直言。
    • 我也是 BeautifulSoup 的粉丝,但它看起来确实像渡渡鸟一样:stackoverflow.com/questions/1922032/…
    • 如果你没有构建任何“关键”的东西,你仍然可以毫无问题地使用漂亮的汤。但是,最新的(3.1.0)版本有很多变化。如果要使用BS,我建议使用3.0.8。
    【解决方案2】:

    如果这是你的整个 HTML,那么这就足够了:

    import BeautifulSoup
    soup = BeautifulSoup.BeautifulSoup("...your HTML...")
    print soup.table['width'], soup.table['height']
    # prints: 600 700
    

    如果你需要先搜索表,也没有那么复杂:

    table = soup.find('table', id='t_id')
    print table['width'], table['height']
    

    【讨论】:

      猜你喜欢
      • 2011-02-26
      • 2011-09-23
      • 2011-06-19
      • 2014-10-21
      • 2011-07-12
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多