问题描述
我刚刚开始尝试将 scrapy 与 BeautifulSoup 我想知道我是否遗漏了一些非常明显的东西,但我似乎无法弄清楚如何获得 a 的 doctype从结果汤对象返回 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.
给定以下 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 从中提取声明的文档类型?
Can anyone tell me if there's a way of extracting the declared doctype from it using BeautifulSoup?
推荐答案
Beautiful Soup 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!