【问题标题】:How to extract the table and it's values using BeautifulSoup4如何使用 BeautifulSoup4 提取表格及其值
【发布时间】:2018-03-07 01:03:34
【问题描述】:

如何使用 BeautifulSoup 提取表格及其值?尝试遵循 bs4 文档,但在查找 classth 值时遇到问题。我如何才能从整个 HTML 页面中显式获取 {underReplicatedBlocks} 值。

<div class="page-header"><h1><small>Decommissioning</small></h1></div>
<small>
<table class="table">
  <thead>
    <tr>
      <th>Node</th>
      <th>Last contact</th>
      <th>Under replicated blocks</th>
      <th>Blocks with no live replicas</th>
      <th>Under Replicated Blocks <br/>In files under construction</th>
    </tr>
  </thead>
  {#DecomNodes}
  <tr>
    <td>{name} ({xferaddr})</td>
    <td>{lastContact}</td>
    <td>{underReplicatedBlocks}</td>
    <td>{decommissionOnlyReplicas}</td>
    <td>{underReplicateInOpenFiles}</td>
  </tr>
  {/DecomNodes}
</table>
</small>

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    如果您正在抓取的文档中的 tr 属性在每 3 行中,那么您可以使用此选项:

    rows = soup.findAll('tr')[2::3]
    

    【讨论】:

      【解决方案2】:

      由于您想要的标签没有特殊的类,您将不得不通过查看 HTML 来获取索引并对它们进行硬编码。查看表格,检查哪一行 (&lt;tr&gt;) 是所需的文本;对列进行同样的操作。

      因为它位于第二行第三列,所以你必须使用这个:

      table = soup.find('table', class_='table')
      rows = table.find_all('tr')
      required_row = rows[1]
      columns = required_row.find_all('td')
      required_column = columns[2]
      required_text = required_column.text
      

      或者,简单地说:

      required_text = table.find_all('tr')[1].find_all('td')[2].text
      print(required_text)
      # {underReplicatedBlocks}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-28
        • 2019-02-19
        • 2018-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-05
        • 1970-01-01
        相关资源
        最近更新 更多