【问题标题】:Beautifulsoup xml美丽的汤xml
【发布时间】:2015-10-15 07:44:07
【问题描述】:

我正在尝试使用此代码将一个简单的信息添加到 xml 树中,该信息在表格中。每个文件都有我需要添加到其中的 id。 corresp 字典有文件名和 id 对。 xml中已经有一个空元素,叫idno[@type='TM'],我需要在里面输入对应的id号。

from bs4 import BeautifulSoup

DIR = 'files/'
corresp = {"00100004":"362375", "00100005":"362376", "00100006":"362377", "00100007":"362378"}

for fileName, tm in corresp.iteritems():
    soup = BeautifulSoup(open(DIR + fileName + ".xml")) 
    tmid = soup.find("idno", type="TM")
    tmid.append(tm)
    print soup

我的第一个问题是有时它会起作用,有时它会说

tmid.append(tm)
AttributeError: 'NoneType' object has no attribute 'append'

我不知道为什么。昨天晚上我运行了相同的示例代码,现在它以这种方式抱怨。

我也试过etree

import xml.etree.ElementTree as ET
DIR = 'files/'
corresp = {"00100004":"362375", "00100005":"362376", "00100006":"362377", "00100007":"362378"}
for fileName, tm in corresp.iteritems():
        f = open(DIR + fileName + ".xml")
        tree = ET.parse(f)
        tmid = tree.findall("//idno[@type='TM']")
        tmid.append(tm)
        tree.write('output.xml', encoding='utf-8', xml_declaration=True)

但它说“找不到元素:第 1 行,第 0 列”

我的第二个可能相关的问题是,当它工作时,我无法将输出写入文件。理想情况下,我想简单地将其写回我正在修改的文件中。

非常感谢您对此提供任何建议。

【问题讨论】:

  • try ---from bs4 import BeautifulSoup import os DIR = 'files/' root = os.path.abspath(DIR) corresp = {"00100004":"362375", "00100005":" 362376", "00100006":"362377", "00100007":"362378"} for fileName, tm in corresp.iteritems(): soup = BeautifulSoup(open(os.path.join(root,"fileName",". xml"))) tmid = soup.find("idno", type="TM") tmid.append(tm) 打印汤

标签: python xml io beautifulsoup


【解决方案1】:

第一个问题:

find() 只是返回结果。如果 find() 找不到任何东西,则返回 None。 result 和 None 都不是 python 列表,因此它没有 append() 方法。

检查文档: http://www.crummy.com/software/BeautifulSoup/bs4/doc/

【讨论】:

  • Find 永远不会返回列表,因此即使找到了某些东西,它也会引发异常(不是同一个 exc)。 Find_all 返回列表或空列表..
  • 我明白了,也就是说文件中没有idno?实际上......如何将更改保存到文件中?
  • @PietroMariaLiuzzo,anwser 已更新,关于您的第二个问题的回溯信息是什么?
  • 谢谢大家!实际上是这样:在以前的一些尝试中,我以某种方式清空了一个文件,这显然阻止了一切,因为在那里找不到 idno[@type='TM'] 。至于第二个问题,我显然已经设法用另外一个变量来解决它。这对于文件名,tm in corresp.iteritems(): myfile = open(DIR + fileName + ".xml") soup = BeautifulSoup(myfile) tmid = soup.find("idno", type="TM") tmid。 append(tm) new = soup.prettify("UTF-8") myfile.close() with open(NewDIR + fileName + ".xml", "wb") as file: file.write(new)
猜你喜欢
  • 2021-01-15
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 2010-10-27
  • 2020-12-13
相关资源
最近更新 更多