【问题标题】:xml parsing terminated inexplicablyxml解析莫名其妙终止
【发布时间】:2013-06-13 09:57:19
【问题描述】:

我有一个文件,其中包含用格式良好的 XML 包装的句子(xmllint 和 tidylib 是这样说的)。 所以xml看起来像这样:

<a id="100" attr1="text" attr1="text" attr1="text">
<tagname id="1">
This is my sentence.
</tagname>
</a>
<a id="101" attr1="text" attr1="text" attr1="text">
<tagname id="1">
This is my sentence.
</tagname>
</a>

等等。

我使用下面的代码提取带有属性的句子(本例中从id 1到85)

a1 = open(r"file.xml",'r')
a = a1.readlines()
a1.close()
soup = BeautifulSoup(str(a))
for i in range(1,85):
    a = soup.find('a', {'id': i})
    achild = a.find('tagname')
    tagnametext = achild.contents
    print tagnametext

一切都打印得很好,直到第 84 句我收到错误: achild = a.find('tagname') AttributeError: 'NoneType' 对象没有属性 'find'

每组 ... 都是用 for 循环生成的,所以 xml 都是一样的。 我尝试过使用不同数量的句子的不同文件。发生错误的 id 也会发生变化。 这是beautifulsoup的限制吗? 它不能扫描超过一定数量的行?

【问题讨论】:

  • id 84 长什么样子?

标签: python xml beautifulsoup


【解决方案1】:

它在最后一行失败。这可能是文件编码问题,该行包含一些有趣的 EOF 字符,或者该行没有被解释为字符串。你能在它失败之前打印出最后一行,看看它是什么类型吗?

【讨论】:

    【解决方案2】:

    a = soup.find('a', {'id': i})84 很可能不会返回您期望的结果。 find()如果找不到标签则返回None,从而解释AttributeError

    另外,在您的代码中,您似乎正在 BeautifulSouping 一个列表(表示为一个字符串)。

    soup = BeautifulSoup(str(a))
    

    你在串起一个列表,然后给列表加汤,这很愚蠢。如果它有一个id,那么汤整个文件然后循环遍历每个标签怎么样?

    from bs4 import BeautifulSoup
    with open('file.xml', 'r') as myfile:
        soup = BeautifulSoup(myfile.read())
        for i in soup.find_all('a', id=True):
            print i.tagname.contents
    

    打印:

    [u'\nThis is my sentence.\n']
    [u'\nThis is my sentence.\n']
    

    【讨论】:

    • soup = BeautifulSoup(myfile.read()) 使我的 python IDLE GUI 崩溃。该文件包含大约 140,000 个句子
    • @waterling 那时可能不是最好的选择。
    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 2012-03-12
    • 2019-02-04
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多