ファイルが本当にXMLファイルの場合は、XMLヘッダーが含まれている必要があります。
されていない場合、あなたはパーサとしてlxml
を使用することができます:あなたがファイルから読み込まれたときに、あなたがして、それがよりエレガントにすることができますので、あなたがより良い、コンテキスト(with
)を使用
from bs4 import BeautifulSoup
infile = open("testA.xml",'r')
contents = infile.read()
soup=BeautifulSoup(contents,'lxml')
result = soup.find_all('a')
print(result)
マインド:
from bs4 import BeautifulSoup
with open("testA.xml",'r') as infile:
contents = infile.read()
soup=BeautifulSoup(contents,'lxml')
result = soup.find_all('a')
print(result)
これはwith
スコープの飛び出し一度ファイルを閉じるにはPythonを強制します。 python3でこれを実行する
ができます:
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from bs4 import BeautifulSoup
>>> infile = open("testA.xml",'r')
>>> contents = infile.read()
>>> soup=BeautifulSoup(contents,'lxml')
>>> result = soup.find_all('a')
>>> result
[<a>
<b>1</b>
</a>, <a>
<b>2</b>
</a>, <a>
<b>3</b>
</a>]
は、あなたのファイルは、XMLヘッダを含めることはできませんか? –
yaそうです、私はファイルを書く関数があり、xml-headerを書くのを忘れました@WillemVanOnsem – 1pa
@ 1pati2: 'lxml'を使うこともできます。その場合、ヘッダーは必要ありません。 –