使用BeautifulSoup从XML文件读取CDATA
我将推文保存在XML文件中,如下所示:使用BeautifulSoup从XML文件读取CDATA,xml,python-3.x,beautifulsoup,Xml,Python 3.x,Beautifulsoup,我将推文保存在XML文件中,如下所示: <tweet> <tweetid>142389495503925248</tweetid> <user>ccifuentes</user> <content><![CDATA[Salgo de #VeoTV , que día más largoooooo...]]></content> <date>2011-12-02T00:47:
<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>
其中xml是原始xml文件。要访问单个tweet,我做了以下操作:
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>
142389495503925248
赛富恩特斯
2011-12-02T00:47:55
锿
非协议
奥特罗斯
请注意,当我打印第一条tweet时,CDATA部分被省略了。这对我来说很重要,我怎么能做到
soup = bs4.BeautifulSoup(xml, 'xml')
将解析器更改为xml
输出:
输出:
干杯,解析器之间的主要区别是什么?@Vladimir Vargas不同的解析器在数据类型的某些部分的行为不同,在大多数情况下,它们都是相同的。
soup = bs4.BeautifulSoup(xml, 'xml')
<content>Salgo de #VeoTV , que día más largoooooo...</content>
soup = bs4.BeautifulSoup(xml, 'html.parser')
<content><![CDATA[Salgo de #VeoTV , que día más largoooooo...]]></content>