【发布时间】:2016-12-09 17:52:42
【问题描述】:
我有一个简单的 HTML 表来解析,但不知何故,Beautifulsoup 只能从最后一行得到结果。我想知道是否有人会看一下,看看有什么问题。所以我已经从 HTML 表中创建了 rows 对象:
<table class='participants-table'>
<thead>
<tr>
<th data-field="name" class="sort-direction-toggle name">Name</th>
<th data-field="type" class="sort-direction-toggle type active-sort asc">Type</th>
<th data-field="sector" class="sort-direction-toggle sector">Sector</th>
<th data-field="country" class="sort-direction-toggle country">Country</th>
<th data-field="joined_on" class="sort-direction-toggle joined-on">Joined On</th>
</tr>
</thead>
<tbody>
<tr>
<th class='name'><a href="/what-is-gc/participants/4479-Grontmij">Grontmij</a></th>
<td class='type'>Company</td>
<td class='sector'>General Industrials</td>
<td class='country'>Netherlands</td>
<td class='joined-on'>2000-09-20</td>
</tr>
<tr>
<th class='name'><a href="/what-is-gc/participants/4492-Groupe-Bial">Groupe Bial</a></th>
<td class='type'>Company</td>
<td class='sector'>Pharmaceuticals & Biotechnology</td>
<td class='country'>Portugal</td>
<td class='joined-on'>2004-02-19</td>
</tr>
</tbody>
</table>
我使用以下代码获取行:
table=soup.find_all("table", class_="participants-table")
table1=table[0]
rows=table1.find_all('tr')
rows=rows[1:]
这得到:
rows=[<tr>
<th class="name"><a href="/what-is-gc/participants/4479-Grontmij">Grontmij</a></th>
<td class="type">Company</td>
<td class="sector">General Industrials</td>
<td class="country">Netherlands</td>
<td class="joined-on">2000-09-20</td>
</tr>, <tr>
<th class="name"><a href="/what-is-gc/participants/4492-Groupe-Bial">Groupe Bial</a></th>
<td class="type">Company</td>
<td class="sector">Pharmaceuticals & Biotechnology</td>
<td class="country">Portugal</td>
<td class="joined-on">2004-02-19</td>
</tr>]
正如预期的那样,它看起来像。但是,如果我继续:
for row in rows:
cells = row.find_all('th')
我只能得到最后一个条目!
cells=[<th class="name"><a href="/what-is-gc/participants/4492-Groupe-Bial">Groupe Bial</a></th>]
发生了什么事?这是我第一次使用beautifulsoup,我想做的是将这个表导出为CSV。任何帮助是极大的赞赏!谢谢
【问题讨论】:
-
rows是如何定义的? -
谢谢!提供了有关表格和代码的更多详细信息。
-
它正在做你要求它做的事情。您是否要获取所有
td的信息?
标签: python html parsing beautifulsoup