gpt4 book ai didi

python - 使用 BS4 抓取未关闭的元标签

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:34 39 4
gpt4 key购买 nike

我正在尝试获取元标记的内容。问题是 BS4 无法在某些网站上正确解析标签,标签没有按应有的方式关闭。使用标签作为下面的示例,我的函数的输出包括大量困惑,包括其他标签,如脚本、链接等。我相信浏览器会自动关闭头部末尾某处的元标签,这种行为会混淆 BS4。

我的代码适用于此:

<meta name="description" content="content" />

不适用于:

<meta name="description" content="content">

这是我的 BS4 函数的代码:

from bs4 import BeautifulSoup

html = BeautifulSoup(open('/path/file.html'), 'html.parser')
desc = html.find(attrs={'name':'description'})

print(desc)

有什么方法可以让它与那些未关闭的元标记一起使用?

最佳答案

html5lib or lxml parser会妥善处理问题:

In [1]: from bs4 import BeautifulSoup
...:
...: data = """
...: <html>
...: <head>
...: <meta name="description" content="content">
...: <script>
...: var i = 0;
...: </script>
...: </head>
...: <body>
...: <div id="content">content</div>
...: </body>
...: </html>"""
...:

In [2]: BeautifulSoup(data, 'html.parser').find(attrs={'name': 'description'})
Out[2]: <meta content="content" name="description">\n<script>\n var i = 0;\n </script>\n</meta>

In [3]: BeautifulSoup(data, 'html5lib').find(attrs={'name': 'description'})
Out[3]: <meta content="content" name="description"/>

In [4]: BeautifulSoup(data, 'lxml').find(attrs={'name': 'description'})
Out[4]: <meta content="content" name="description"/>

关于python - 使用 BS4 抓取未关闭的元标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40509708/

39 4 0