Python 使用BeautifulSoup获取文档DOCTYPE

Python 使用BeautifulSoup获取文档DOCTYPE,python,parsing,beautifulsoup,scrapy,Python,Parsing,Beautifulsoup,Scrapy,我刚刚开始结合修补,我想知道我是否遗漏了一些非常明显的东西,但我似乎不知道如何从生成的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 /> <me

我刚刚开始结合修补,我想知道我是否遗漏了一些非常明显的东西,但我似乎不知道如何从生成的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>

HTML5演示和示例

这是第一段 这是第二段。


有谁能告诉我,是否有一种方法可以使用BeautifulSoup从中提取声明的doctype?

您只需获取汤内容中的第一项:

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

您可以遍历顶级元素并检查每个元素是否是声明。然后您可以检查它以了解它是什么类型的声明:

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

Beautiful Soup 4有一个用于DOCTYPE声明的类,因此您可以使用该类来提取顶级的所有声明(尽管您无疑希望有一个或没有!)


小心,如果doctype不是第一项,则此语法将中断。例如,当文档顶部有一个xml声明时,这可能会返回任何内容,因为doctype可能会丢失,而且经常会丢失。
def doctype(soup):
    items = [item for item in soup.contents if isinstance(item, bs4.Doctype)]
    return items[0] if items else None