获取与BeautifulSoup文件DOCTYPE [英] Get document DOCTYPE with BeautifulSoup
问题描述
我刚刚开始 scrapy 用的 BeautifulSoup ,我想知道如果我失去了一些东西很明显,但我似乎无法弄清楚如何摆脱由此产生的汤对象返回的HTML文档的文档类型。
I've just started tinkering with scrapy in conjunction with BeautifulSoup and I'm wondering if I'm missing something very obvious but I can't seem to figure out how to get the doctype of a returned html document from the resulting soup object.
由于fllowing HTML:
Given the fllowing 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从中提取DOCTYPE声明的一种方式?
Can anyone tell me if there's a way of extracting the declared doctype from it using BeautifulSoup?
干杯。
推荐答案
美丽的汤4有DOCTYPE声明一个类,所以你可以用它来在顶级提取所有的声明(虽然你无疑期待一个或没有!)
Beautiful Soup 4 has a class for DOCTYPE declarations, so you can use that to extract all the declarations at top level (though you're no doubt expecting one or none!)
def doctype(soup):
items = [item for item in soup.contents if isinstance(item, bs4.Doctype)]
return items[0] if items else None
这篇关于获取与BeautifulSoup文件DOCTYPE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!