【问题标题】:How can I prevent closing of tags in bad HTML using BeautifulSoup (python)?如何使用 BeautifulSoup (python) 防止关闭坏 HTML 中的标签?
【发布时间】:2011-11-20 01:42:09
【问题描述】:

我会自动将 HTML 页面的内容翻译成不同的语言,因此我必须从不同的 HTML 页面中提取所有文本节点,这些页面有时写得不好(我无法编辑这些 HTML)。

通过使用 BeautifulSoup,我可以轻松提取这些文本并用翻译替换它,但是当我在这些操作之后显示 HTML 时: html = BeautifulSoup(source_html) - 它有时会因为 BeautifulSoup 自动关闭标签而损坏(例如表标签在错误的位置关闭) .

有没有办法阻止 BeautifulSoup 关闭这些标签?

例如这是我的输入:

html = "<table><tr><td>some text</td></table>" - 缺少关闭 tr

在汤 = BeautufulSoup(html) 之后我得到 "<table><tr><td>some text</td></tr></table>"

我想获得与输入完全相同的 html...

有可能吗?

【问题讨论】:

  • 例如这是我的输入: html = "some text" - 在 soup = BeautufulSoup(html) 之后缺少关闭 tr 我得到“一些文本”并且我想获得与输入相同的 html ...有可能吗?
  • 要添加示例,请更新您的问题并确保将其格式化为代码,否则标签将不会显示。

标签: python parsing html-parsing beautifulsoup


【解决方案1】:

BeautifulSoup 擅长从格式错误的 HTML/XML 中解析和提取数据,但如果损坏的 HTML 不明确,那么它会使用一组规则来解释标签(这可能不是您想要的)。请参阅文档中关于 Parsing HTML 的部分,该部分以一个听起来与您的情况非常相似的示例结尾。

如果您知道您的标签有什么问题并了解 BeautifulSoup 使用的规则,您可以稍微增强您的 HTML(可能删除或移动某些标签)以使 BeautifulSoup 返回您想要的输出。

如果你能发布一个简短的例子,有人可能会给你更具体的帮助。


更新(一些例子)

例如,考虑文档(上面链接)中给出的示例:

from BeautifulSoup import BeautifulSoup
html = """
<html>
<form>
 <table>
 <td><input name="input1">Row 1 cell 1
 <tr><td>Row 2 cell 1
 </form> 
 <td>Row 2 cell 2<br>This</br> sure is a long cell
</body> 
</html>"""
print BeautifulSoup(html).prettify()

&lt;table&gt; 标记将在 &lt;/form&gt; 之前关闭,以确保表格正确嵌套在表单中,而最后一个 &lt;td&gt; 则挂起。

如果我们理解了问题所在,我们可以通过在解析前删除"&lt;form&gt;"来获得正确的关闭标签(&lt;/table&gt;):

>>> html = html.replace("<form>", "")
>>> soup = BeautifulSoup(html)
>>> print soup.prettify()
<html>
 <table>
  <td>
   <input name="input1" />
   Row 1 cell 1
  </td>
  <tr>
   <td>
    Row 2 cell 1
   </td>
   <td>
    Row 2 cell 2
    <br />
    This
    sure is a long cell
   </td>
  </tr>
 </table>
</html>

如果&lt;form&gt;标签很重要,解析后仍然可以添加。例如:

>>> new_form = Tag(soup, "form")  # create form element
>>> soup.html.insert(0, new_form)  # insert form as child of html
>>> new_form.insert(0, soup.table.extract()) # move table into form
>>> print soup.prettify()
<html>
 <form>
  <table>
   <td>
    <input name="input1" />
    Row 1 cell 1
   </td>
   <tr>
    <td>
     Row 2 cell 1
    </td>
    <td>
     Row 2 cell 2
     <br />
     This
     sure is a long cell
    </td>
   </tr>
  </table>
 </form>
</html>

【讨论】:

    猜你喜欢
    • 2015-03-24
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多