我刚刚开始与BeautifulSoup结合使用scrapy,我想知道是否遗漏了一些非常明显的内容,但似乎无法弄清楚如何从生成的汤对象中获取返回的html文档的文档类型。
鉴于以下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的方法?
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