質問

まだいじり始めたばかりです こすれた と組み合わせて 美しいスープ そして、非常に明らかな何かが欠けているのではないかと思っていますが、結果として得られるスープオブジェクトから返された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を抽出する方法があるかどうか誰かが教えてくれますか?

役に立ちましたか?

解決

Beautiful Soup 4 には DOCTYPE 宣言用のクラスがあるため、それを使用してトップレベルのすべての宣言を抽出できます (ただし、1 つも期待することも、まったく期待しないことも間違いありません)。

def doctype(soup):
    items = [item for item in soup.contents if isinstance(item, bs4.Doctype)]
    return items[0] if items else None

他のヒント

最上位の要素を調べて、それぞれをチェックして、それが宣言であるかどうかを確認できます。次に、それを検査して、どのような種類の宣言であるかを確認できます。

for child in soup.contents:
    if isinstance(child, BS.Declaration):
        declaration_type = child.string.split()[0]
        if declaration_type.upper() == 'DOCTYPE':
            declaration = child

スープの内容の最初の項目を取得するだけです。

>>> soup.contents[0]
u'DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"'
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top