【发布时间】:2011-01-24 13:22:18
【问题描述】:
使用beautifulsoup解析html中的表格时,每隔一行开始
<tr class="row_k">
而不是没有类的 tr 标签
示例 HTML
<tr class="row_k">
<td><img src="some picture url" alt="Item A"></td>
<td><a href="some url"> Item A</a></td>
<td>14.8k</td>
<td><span class="drop">-555</span></td>
<td>
<img src="some picture url" alt="stuff" title="stuff">
</td>
<td>
<img src="some picture url" alt="Max llll">
</td>
</tr>
<tr>
<td><img src="some picture url" alt="Item B"></td>
<td><a href="some url"> Item B</a></td>
<td>64.9k</td>
<td><span class="rise">+165</span></td>
<td>
<img src="some picture url" alt="stuff" title="stuff">
</td>
<td>
<img src="some picture url" alt="max llll">
</td>
</tr>
<tr class="row_k">
<td><img src="some picture url" alt="Item C"></td>
<td><a href="some url"> Item C</a></td>
<td>4,000</td>
<td><span class="rise">+666</span></td>
<td>
<img src="some picture url" title="stuff">
</td>
<td>
<img src="some picture url" alt="Maximum lllle">
我要提取的文本是 14.8k、64.9k 和 4,000
this1 = urllib2.urlopen('my url').read()
this_1 = BeautifulSoup(this1)
this_1a = StringIO.StringIO()
for row in this_1.findAll("tr", { "class" : "row_k" }):
for col in row.findAll(re.compile('td')):
this_1a.write(col.string if col.string else '')
Item_this1 = this_1a.getvalue()
我感觉这段代码写得不好,有没有更灵活的工具可以使用,比如 XML 解析器?有人可以建议。
仍然对仍然使用 beautifulsoup 的任何答案持开放态度。
【问题讨论】:
-
如果包含更多的 html 会更容易。我认为您是在说表格正文中有一个锚标记,并且表格中锚选项卡之后的下一列包含您想要的数据。
-
我做了一个样本。我正在使用 beautifulsoup 来执行此操作,但问题是表中的所有其他列都有 tr class="row_k" 所以它忽略它并且不会给我来自 tr 标签的信息。我会更新我的问题。
标签: python xml tags urllib2 beautifulsoup