使用BeautifulSoup获取文档DOCTYPE

Ste*_*ike 7 python parsing beautifulsoup scrapy

我刚刚开始与BeautifulSoup一起修补scrapy,我想知道我是否遗漏了一些非常明显的东西,但我似乎无法弄清楚如何从生成的汤对象中获取返回的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>
Run Code Online (Sandbox Code Playgroud)

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

rpt*_*tb1 6

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
Run Code Online (Sandbox Code Playgroud)