使用BeautifulSoup从XML文件读取CDATA [英] Reading CDATA from XML file with BeautifulSoup
本文介绍了使用BeautifulSoup从XML文件读取CDATA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在XML文件中保存了以下推文:
I have tweets saved in an XML file as:
<tweet>
<tweetid>142389495503925248</tweetid>
<user>ccifuentes</user>
<content><![CDATA[Salgo de #VeoTV , que día más largoooooo...]]></content>
<date>2011-12-02T00:47:55</date>
<lang>es</lang>
<sentiments>
<polarity><value>NONE</value><type>AGREEMENT</type></polarity>
</sentiments>
<topics>
<topic>otros</topic>
</topics>
</tweet>
要解析这些内容,我通过创建一个BeautifulSoup实例
To parse these, I created a BeautifulSoup instance via
soup = BeautifulSoup(xml, "lxml")
其中xml是原始XML文件.要访问一条推文,我这样做:
where xml is the raw XML file. To access a single tweet I did this:
tweets = soup.find_all('tweet')
for tw in tweets:
print(tw)
break
这将导致
<tweet>
<tweetid>142389495503925248</tweetid>
<user>ccifuentes</user>
<content></content>
<date>2011-12-02T00:47:55</date>
<lang>es</lang>
<sentiments>
<polarity><value>NONE</value><type>AGREEMENT</type></polarity>
</sentiments>
<topics>
<topic>otros</topic>
</topics>
</tweet>
请注意,当我打印第一条Tweet时,省略了CDATA部分.对我来说很重要,我该怎么办?
Note that the CDATA part was omitted when I printed the first tweet. It is important for me to get it, how can I do this?
推荐答案
soup = bs4.BeautifulSoup(xml, 'xml')
将解析器更改为 xml
退出:
<content>Salgo de #VeoTV , que día más largoooooo...</content>
或 html.parser
:
soup = bs4.BeautifulSoup(xml, 'html.parser')
退出:
<content><![CDATA[Salgo de #VeoTV , que día más largoooooo...]]></content>
这篇关于使用BeautifulSoup从XML文件读取CDATA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文