2013-02-19 10 views
8

この質問は、前の質問から、それは違うた、BeautifulSoup4に固有のものです:BeautifulStoneSoup以来BeautifulSoup 4を自己クローズするタグを尊重するにはどうすればよいですか?

Why is BeautifulSoup modifying my self-closing elements?

selfClosingTags in BeautifulSoup

が(前回のXMLパーサー)なくなって、私が尊敬するbs4を取得する方法新しい自己閉鎖タグ?たとえば:

import bs4 
S = '''<foo> <bar a="3"/> </foo>''' 
soup = bs4.BeautifulSoup(S, selfClosingTags=['bar']) 

print soup.prettify() 

は自己クローズbarタグをしませんが、ヒントを与えます。 bs4が参照しているこのツリービルダーと、タグを自己クローズする方法は何ですか?

/usr/local/lib/python2.7/dist-packages/bs4/__init__.py:112: UserWarning: BS4 does not respect the selfClosingTags argument to the BeautifulSoup constructor. The tree builder is responsible for understanding self-closing tags. 
    "BS4 does not respect the selfClosingTags argument to the " 
<html> 
<body> 
    <foo> 
    <bar a="3"> 
    </bar> 
    </foo> 
</body> 
</html> 

答えて

12

To parse XML you pass in “xml” as the second argument to the BeautifulSoup constructor.

soup = bs4.BeautifulSoup(S, 'xml') 

You’ll need to have lxml installed.

あなたはもうselfClosingTagsを渡す必要はありません:それはまだこれは `selfClosingTags`のリストを渡すことで動作します

In [1]: import bs4 
In [2]: S = '''<foo> <bar a="3"/> </foo>''' 
In [3]: soup = bs4.BeautifulSoup(S, 'xml') 
In [4]: print soup.prettify() 
<?xml version="1.0" encoding="utf-8"?> 
<foo> 
<bar a="3"/> 
</foo> 
+0

が、上記と同じ警告を出します。私は何か間違っているのですか? – Hooked

+0

問題がなければ、その質問に回答します。コンテンツが空でリストが渡されるべきでないときには、xmlモードのself-closingタグが自動的に作成されるようです。 – Hooked

+0

右。デモを追加しました。 –

関連する問題