我有以下xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><author id="user23">
<document><![CDATA["@username: That boner came at the wrong time ???? http://t.co/5X34233gDyCaCjR" HELP I'M DYING ]]></document>
<document><![CDATA[Ugh ]]></document>
<document><![CDATA[YES !!!! WE GO FOR IT. http://t.co/fiI23324E83b0Rt ]]></document>
<document><![CDATA[@username Shout out to me???? ]]></document>
</author>
将<![CDATA[
内容]]>
解析并提取到列表中的最有效方法是什么。比如说:
这就是我所尝试的:
from bs4 import BeautifulSoup
x='/Users/user/PycharmProjects/TratandoDeMejorarPAN/test.xml'
y = BeautifulSoup(open(x), 'xml')
out = [y.author.document]
print out
这是输出:
[<document>"@username: That boner came at the wrong time ???? http://t.co/5XgDyCaCjR" HELP I'M DYING </document>]
这个输出的问题是我不应该得到<document></document>
。如何删除<document></document>
标记并在列表中获取此xml的所有元素?。在
这里有几件事不对劲。(关于选择库的问题在这里是违反规则的,所以我忽略了这部分问题)。在
您需要传入一个文件句柄,而不是一个文件名称。在
即:
y = BeautifulSoup(open(x))
您需要告诉beauthulsoup它正在处理XML。在
即:
y = BeautifulSoup(open(x), 'xml')
CDATA
节不创建元素。不能在DOM中搜索它们,因为它们不存在于DOM中;它们只是语法上的糖。只需查看document
下的文本,不要试图搜索名为CDATA
的内容。在再说一遍,稍微有点不同:}的{}部分,还是包含{}和{}的原始文本部分。这是设计的,任何兼容的xmldom实现都是如此。
<doc><![CDATA[foo]]</doc>
与<doc>foo</doc>
完全相同。关于CDATA
部分的不同之处在于它里面的所有内容都是自动转义的,这意味着<![CDATA[<hello>]]
被解释为<hello>
。但是,您无法从解析的对象树中分辨出您的文档是包含文本为<
和{现在,一些实际工作的代码如何:
如果要读取文件,请将
doc
替换为open(filename, 'r')
。在相关问题 更多 >
编程相关推荐