gpt4 book ai didi

python - 如何使用 BeautifulSoup (python) 防止关闭错误 HTML 中的标签?

转载 作者:太空宇宙 更新时间:2023-11-03 11:09:58 26 4
gpt4 key购买 nike

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

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

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

例如这是我的输入:

html = "<table><tr><td>some text</td></table>" - 缺少结束 tr

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

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

有可能吗?

最佳答案

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()

<table>标签将在 </form> 之前关闭确保表格正确嵌套在表格中,留下最后一个 <td>挂着。

如果我们理解这个问题,我们可以通过删除 </table> 来获得正确的关闭标签 ( "<form>" )解析前:

>>> 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>

如果<form>标签很重要,你仍然可以在解析后添加它。例如:

>>> 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>

关于python - 如何使用 BeautifulSoup (python) 防止关闭错误 HTML 中的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7468416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com