【问题标题】:BeautifulSoup: How to extract data after specific html tagBeautifulSoup:如何在特定的 html 标签之后提取数据
【发布时间】:2012-07-23 18:29:59
【问题描述】:

我有以下 html,我试图弄清楚我如何准确地告诉 BeautifulSoup 在某些 html 元素之后提取 td。在这种情况下,我想在<td>Color Digest</td> 之后获取<td> 中的数据

<tr>
<td> Color Digest </td>
<td> 2,36,156,38,25,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, </td>
</tr>

这是整个 HTML

<html>
<head>
<body>
<div align="center">
<table cellspacing="0" cellpadding="0" style="clear:both; width:100%;margin:0px; font-size:1pt;">
<br>
<br>
<table>
<table>
<tbody>
<tr bgcolor="#AAAAAA">
<tr>
<tr>
<tr>
<tr>
<tr>
<tr>
<tr>
<tr>
<tr>
<tr>
<tr>
<tr>
<td> Color Digest </td>
<td> 2,36,156,38,25,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, </td>
</tr>
</tbody>
</table>

【问题讨论】:

  • 这是您的全部 HTML 吗?还是它与许多其他 和 位于一个更大的文件中?是否保证您正在解析的 html 中只有一个“颜色摘要”元素?
  • 不,这只是html的一个sn-p,所以我想真正获得在某个元素之后获取元素的机制。就像在 XPath 中一样,您可以告诉我在 Color Digest 之后需要第一个 td

标签: python html beautifulsoup scrape


【解决方案1】:

听起来您需要遍历&lt;td&gt; 的列表并在找到数据后停止。

例子:

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup('<html><tr><td>X</td><td>Color Digest</td><td>THE DIGEST</td></tr></html>')
for cell in soup.html.tr.findAll('td'):
    if 'Color Digest' == cell.text:
         print cell.nextSibling.text

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签