我有以下XML文件:
<user-login-permission>true</user-login-permission>
<total-matched-record-number>15000</total-matched-record-number>
<total-returned-record-number>15000</total-returned-record-number>
<active-user-records>
<active-user-record>
<active-user-name>username</active-user-name>
<authentication-realm>realm</authentication-realm>
<user-roles>Role</user-roles>
<user-sign-in-time>date</user-sign-in-time>
<events>0</events>
<agent-type>text</agent-type>
<login-node>node</login-node>
</active-user-record> 有许多记录我试图从标记中获取值,并使用以下代码将它们保存在不同的文本文件中:
soup = BeautifulSoup(open("path/to/xmlfile"), features="xml")
with open('path/to/outputfile', 'a') as f:
for i in range(len(soup.findall('active-user-name'))):
f.write ('%s\t%s\t%s\t%s\n' % (soup.findall('active-user-name')[i].text, soup.findall('authentication-realm')[i].text, soup.findall('user-roles')[i].text, soup.findall('login-node')[i].text))我得到错误TypeError:'NoneType‘object not callable Python with active XML for line : for I in range(len(soup.findall(’BeautifulSoup -user-name‘):
知道是什么原因造成的吗?
谢谢!
发布于 2013-08-02 20:10:35
有许多问题需要解决,首先是您提供的XML文件不是有效的XML -根元素是必需的。
尝试将下面的内容作为XML:
<root>
<user-login-permission>true</user-login-permission>
<total-matched-record-number>15000</total-matched-record-number>
<total-returned-record-number>15000</total-returned-record-number>
<active-user-records>
<active-user-record>
<active-user-name>username</active-user-name>
<authentication-realm>realm</authentication-realm>
<user-roles>Role</user-roles>
<user-sign-in-time>date</user-sign-in-time>
<events>0</events>
<agent-type>text</agent-type>
<login-node>node</login-node>
</active-user-record>
</active-user-records>
</root>现在让我们来看看巨蟒。首先,没有findall方法,它要么是findAll,要么是find_all。如here文档所示,findAll和find_all是等效的
接下来,我建议修改您的代码,这样您就不会经常使用find_all方法-使用find将提高效率,特别是对于大的XML文件。此外,下面的代码更易于阅读和调试:
from bs4 import BeautifulSoup
xml_file = open('./path_to_file.xml', 'r')
soup = BeautifulSoup(xml_file, "xml")
with open('./path_to_output_f.txt', 'a') as f:
for s in soup.findAll('active-user-record'):
username = s.find('active-user-name').text
auth = s.find('authentication-realm').text
role = s.find('user-roles').text
node = s.find('login-node').text
f.write("{}\t{}\t{}\t{}\n".format(username, auth, role, node))希望这能有所帮助。如果你需要进一步的帮助,请让我知道!
发布于 2013-08-02 02:03:29
解决方案很简单:不要使用findall方法--使用find_all。
为什么?因为根本没有findall方法,所以有findAll和find_all,它们是等价的。有关详细信息,请参阅docs。
不过,我同意,错误消息令人困惑。
希望这能有所帮助。
发布于 2014-04-21 07:24:41
在我的版本中,这个问题的修复方法是将BeautifulSoup实例强制转换为类型字符串。您可以执行以下操作:https://groups.google.com/forum/#!topic/comp.lang.python/ymrea29fMFI
您可以使用以下python : From python手册
str(对象)
返回一个字符串,该字符串包含一个对象的良好打印表示。对于字符串,它返回字符串本身。与repr(object)的不同之处在于,str(object)并不总是试图返回eval()可接受的字符串;它的目标是返回可打印的字符串。如果没有给定参数,则返回空字符串,
https://stackoverflow.com/questions/17987948
复制相似问题