【问题标题】:Extraction of tds from table using BeautifulSoup and arranging them in Pandas dataframe together with the table id使用 BeautifulSoup 从表中提取 tds 并将它们与表 id 一起排列在 Pandas 数据框中
【发布时间】:2022-01-18 23:54:32
【问题描述】:

我提取了以下 html 代码:

<table id=table1>

  <thead>
    <tr class="table_columns">
      <th id="header1">
        "Column 1 Title"
      </th>
      <th id="header2">
        "Column 2 Title"
      </th>
    </tr>
  </thead>
  
  <tbody>
    <tr class="evenRow">
      <td headers="header1">firstrowcolumn1data</td>
      <td headers="header2">firstrowcolumn2data</td>
    </tr>
    <tr class="oddRow">
      <td headers="header1">secondrowcolumn1data</td>
      <td headers="header2">secondrowcolumn2data</td>
    </tr>
  </tbody>
</table>

我需要提取表(table1)的表数据和id,然后将它们排列成一个Pandas数据框,类似这样:

id table data
table1 firstrowcolumn1data
table1 firstrowcolumn2data
table1 secondrowcolumn1data
table1 secondrowcolumn2data

【问题讨论】:

    标签: python pandas beautifulsoup html-table


    【解决方案1】:

    试试这个:

    data = []
    for table in s.find_all('table'):
        for td in table.find_all('td'):
            data.append((table.get('id'), td.text))
    df = pd.DataFrame(data, columns=['id', 'table data'])
    

    输出:

    >>> df
           id            table data
    0  table1   firstrowcolumn1data
    1  table1   firstrowcolumn2data
    2  table1  secondrowcolumn1data
    3  table1  secondrowcolumn2data
    

    【讨论】:

    • 嗨@user17242583。我意识到该解决方案会产生重复项。一组具有表的实际 id,而另一组具有“无”作为 id。我检查了我爬取的 html 代码,找不到任何重复的表格。这有什么原因吗?
    • 不确定,@Tipo33。你为什么不就此提出一个新问题,因为在 cmets 中很难讨论。
    猜你喜欢
    • 2022-01-03
    • 2022-01-19
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2020-12-28
    • 2021-01-07
    相关资源
    最近更新 更多