9

BeautifulSoupと組み合わせてスクレイピーをいじり始めたばかりで、非常に明白な何かが欠けているのではないかと思っていますが、結果のスープ オブジェクトから返された 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>

BeautifulSoupを使用して宣言されたdoctypeを抽出する方法があるかどうか誰か教えてもらえますか?

4

3 に答える 3

3

トップレベルの要素を調べて、それぞれをチェックして、それが宣言であるかどうかを確認できます。次に、それを検査して、それがどのような宣言であるかを調べることができます。

for child in soup.contents:
    if isinstance(child, BS.Declaration):
        declaration_type = child.string.split()[0]
        if declaration_type.upper() == 'DOCTYPE':
            declaration = child
于 2011-03-31T09:33:11.233 に答える
-1

スープ コンテンツの最初のアイテムを取得するだけです。

>>> soup.contents[0]
u'DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"'
于 2010-03-23T19:53:40.957 に答える