2016-11-09 6 views
2

メタタグの内容を取得しようとしています。問題は、BS4が、タグが閉じられていないサイトでは、タグを適切に解析できないことです。以下の例のようなタグを使用すると、私の関数の出力にスクリプト、リンクなどの他のタグを含む混乱がたくさん含まれています。BS4で閉鎖されていないメタタグを掻き集める

私のコードはこれで動作します。

<meta name="description" content="content" /> 

とでは動作しません。ここで

<meta name="description" content="content"> 

は私のBS4関数のコードです:

from bs4 import BeautifulSoup 

html = BeautifulSoup(open('/path/file.html'), 'html.parser') 
desc = html.find(attrs={'name':'description'}) 

print(desc) 

任意の方法にそれらの非クローズドメタタグで動作させるには?

答えて

1

html5lib or lxml parser適切に問題を処理します:

In [1]: from bs4 import BeautifulSoup 
    ...: 
    ...: data = """ 
    ...: <html> 
    ...:  <head> 
    ...:   <meta name="description" content="content"> 
    ...:   <script> 
    ...:    var i = 0; 
    ...:   </script> 
    ...:  </head> 
    ...:  <body> 
    ...:   <div id="content">content</div> 
    ...:  </body> 
    ...: </html>""" 
    ...: 

In [2]: BeautifulSoup(data, 'html.parser').find(attrs={'name': 'description'}) 
Out[2]: <meta content="content" name="description">\n<script>\n   var i = 0;\n  </script>\n</meta> 

In [3]: BeautifulSoup(data, 'html5lib').find(attrs={'name': 'description'}) 
Out[3]: <meta content="content" name="description"/> 

In [4]: BeautifulSoup(data, 'lxml').find(attrs={'name': 'description'}) 
Out[4]: <meta content="content" name="description"/> 
+0

ありがとうございました。どちらのパーサーも正しく動作します。 –

0

新しい何かを得ると私はそれが検索を継続する、適切な終了タグなし要素を見つけるBeautifulSoupたびに思う、それはあなたにいくつかの助けを与えることができることを望む持ちます次と次の要素にその親タグの終了時まで、あなたはまだ私の考えを理解していない、とここで私は少しデモを作っtag.Maybe:

hello.html 
<!DOCTYPE html> 
    <html lang="en"> 
    <meta name="description" content="content"> 
    <head> 
     <meta charset="UTF-8"> 
     <title>Title</title> 
    </head> 
    <div> 
    <p class="title"><b>The Dormouse's story</b> 

    <p class="story">Once upon a time there were three little sisters; and their names were 
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, 
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and 
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; 
    and they lived at the bottom of a well.</p> 
    </p></div> 
    </body> 
    </html> 

、あなたが前に行われ、下の結果を見つけるように実行します。

<meta content="content" name="description"> 
<head> 
<meta charset="utf-8"> 
<title>Title</title> 
</meta></head> 
<body> 
... 
</div></body> 
</meta> 

ok! BeautifulSoupは自動的に終了メタタグを生成し、位置は</body>タグの後にありますが、メタの親終了タグ</html>はまだ見えません。つまり、終了タグは開始タグと同じ位置に反映されるはずです。しかし、私はまだ結果で2個の</p>のタグがあり、私がテストを行うので、そのような意見自分自身を納得させる<div>...</div>で唯一の</p>タグがあるので、<p class='title'>終了タグを削除しますが、

c = soup.find_all('p', attrs={'class':'title'}) print(c[0])

を実行した後にすることはできません。それは私が以前に言ったように真実です。

関連する問題