gpt4 book ai didi

python - BeautifulSoup 不处理 anchor 标记内的 HTML 表格

转载 作者:行者123 更新时间:2023-12-01 00:17:31 25 4
gpt4 key购买 nike

考虑示例 HTML 代码:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Testing</title>
</head>
<body>
<a href="https://www.google.com">
<table>
<tr>
<td>Hello</td>
</tr>
</table>
</a>
</body>
</html>

关于使用 BeautifulSoup 对此:html_soup = BeautifulSoup(html_source_code,"lxml")我得到:

<!DOCTYPE html>
<html lang="en">
<title>Testing</title>
</head>
<body>
<a href="https://www.google.com">
</a>
<table>
<tr>
<td>Hello</td>
</tr>
</table>
</body>
</html>

请注意该表如何不再包含在 anchor 标记内,从而改变了输出。

我已经通过在线验证器(例如 https://validator.w3.org/ )运行源代码,并且它们没有返回任何错误或警告,因此我相信 HTML 代码本身没有任何问题。

为什么 BS 会导致此错误,如何修复它?附注由于预定义以及 CSS 和 JS 功能,对我来说(在我的实际用例中)将标签移动到内部元素并不简单。

最佳答案

使用“html.parser”

例如:

from bs4 import BeautifulSoup

html_source_code = """<!DOCTYPE html>
<html lang="en">
<head>
<title>Testing</title>
</head>
<body>
<a href="https://www.google.com">
<table>
<tr>
<td>Hello</td>
</tr>
</table>
</a>
</body>
</html>"""

html_soup = BeautifulSoup(html_source_code,"html.parser")
print(html_soup.prettify(formatter='html'))

输出:

<!DOCTYPE html>
<html lang="en">
<head>
<title>
Testing
</title>
</head>
<body>
<a href="https://www.google.com">
<table>
<tr>
<td>
Hello
</td>
</tr>
</table>
</a>
</body>
</html>

关于python - BeautifulSoup 不处理 anchor 标记内的 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59213989/

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