2017-04-03 87 views
1

有沒有辦法讓beautifulsoup不會在xml文件或<html> </html>標記的開頭添加<?xml version="1.0" encoding="utf-8"?>如何使Beautifulsoup不添加<html>或<?xml ?>

我讀過bs4 doc並試過xml,html和lxml解析器,但結果很相似。 我也測試過soup.find('?xml'),這個沒什麼返回。

$ python 
Python 2.7.5 (default, Aug 2 2016, 04:20:16) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from bs4 import BeautifulSoup 
>>> xml='<tag>value</tag>' 
>>> soup=BeautifulSoup(xml,'xml') 
>>> soup 
<?xml version="1.0" encoding="utf-8"?> <=============== 
<tag>value</tag> 
>>> soup.find('?xml') 
>>> soup=BeautifulSoup(xml,'html') 
>>> soup 
<html><body><tag>value</tag></body></html> <=========== 
>>> soup=BeautifulSoup(xml,'lxml') 
>>> soup 
<html><body><tag>value</tag></body></html> <=========== 
>>> 

回答

1
#You can directly print the tag (or body). Hope this helps. 
from bs4 import BeautifulSoup 
xml='<tag>value</tag>' 
soup=BeautifulSoup(xml,'lxml') 
soup.tag #or soup.body 

#Output: 
<tag>value</tag> 
+0

謝謝!這是唯一可行的方法。 – Yang

相關問題