使用BeautifulSoup获取文档DOCTYPE

9 投票
3 回答
7457 浏览
提问于 2025-04-15 20:44

我刚开始玩 scrapyBeautifulSoup,我在想我是不是漏掉了什么很明显的东西,但我就是搞不清楚怎么从返回的 soup 对象中获取 HTML 文档的文档类型(doctype)。

给定以下 HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en"> 
<head> 
<meta charset=utf-8 />
<meta name="viewport" content="width=620" />
<title>HTML5 Demos and Examples</title> 
<link rel="stylesheet" href="/css/html5demos.css" type="text/css" /> 
<script src="js/h5utils.js"></script> 
</head> 
<body>
<p id="firstpara" align="center">This is paragraph <b>one</b>
<p id="secondpara" align="blah">This is paragraph <b>two</b>.
</html>

有没有人能告诉我,使用 BeautifulSoup 有没有办法从中提取出声明的文档类型?

3 个回答

-1

你可以直接获取汤内容中的第一个项目:

>>> soup.contents[0]
u'DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"'
3

你可以查看最顶层的元素,检查每一个元素,看看它是不是一个声明。然后你可以进一步检查,了解它是什么类型的声明:

for child in soup.contents:
    if isinstance(child, BS.Declaration):
        declaration_type = child.string.split()[0]
        if declaration_type.upper() == 'DOCTYPE':
            declaration = child
7

Beautiful Soup 4 有一个专门处理 DOCTYPE 声明的类,这样你就可以用它来提取所有在最顶层的声明(虽然你可能只会期待有一个或者没有!)

def doctype(soup):
    items = [item for item in soup.contents if isinstance(item, bs4.Doctype)]
    return items[0] if items else None

撰写回答