【问题标题】:HTML parsing with Beautiful soup用美丽的汤进行 HTML 解析
【发布时间】:2012-02-05 19:40:45
【问题描述】:

这就是我的 HTML 的样子:

<table cellspacing="0" cellpadding="0"  class="list04" style="width:704px;">

    <td class="txt"><img src="img/1001.gif" /></td>
    <td>
    <div>string1</div>
    <div>
    string2</div>
    </td>
    <td><div class="name">string3</div>
    </td>
    <td>
    </td>
    <td></td>
    </tr>
    <tr>
    <td></td>


    <td class="txt"><img src="img/1002.gif" /></td>
    <td>
    <div>string4</div>
    <div>
    string5</div>
    </td>
    <td><div class="name">string6</div>
    </td>
    <td>
    </td>
    <td></td>
    </tr>
    <tr>
    <td></td>

</table>

我想用 Beautiful soup 提取字符串(string1 到 string6)。

谁能回答我如何做到这一点?

** 在 HTML 的其余部分中有很多 &lt;div&gt;s,我不需要全部。 我想提取&lt;td class="txt"&gt;和&lt;/td&gt;之间的字符串

【问题讨论】:

  • 要做到这一点,我们需要知道哪些标签封装了这些部分——再给我们一些 HTML。
  • &lt;td class="txt"&gt; 和下一个 &lt;/td&gt; 在同一行中,并且您不包含您要查找的任何 &lt;div&gt;s。您可能想查看一些包含它们的 &lt;tr&gt; 或 &lt;table&gt;。
  • 表看起来像那样.. 很抱歉造成混淆。我想提取表中的所有字符串。 :(

标签: python beautifulsoup


【解决方案1】:

如果它在字符串 html 中,请使用

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
print [t.text for t in soup.find("table", {"class": "list04"}).findAll("div")]

将打印出来:

[u'string1', u'string2', u'string3', u'string4', u'string5', u'string6']

【讨论】:

  • 我不需要的
    太多了。我想提取 和 之间的字符串
  • 那么,您需要向我们展示更多的 HTML。正如您设置的那样, 和相应的 之间的唯一内容是 IMG 标签。剩下的标签是什么?
  • 我会用 t.text 替换 t.contents[0].strip()。
  • 没有其他标签。 我说的是最后一个。
  • 我编辑了我的代码,使其仅从该特定表中提取 div。
【解决方案2】:

试试这个

from BeautifulSoup import BeautifulSoup 
f = open('a.htm')
soup = BeautifulSoup(f) 
anothersoup = BeautifulSoup(soup.findAll('td', attrs={'class':'txt'}))
list = anothersoup.findAll('div')
print list

【讨论】:

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