2015-10-15 68 views
0

我想要使用此代碼將添加到xml樹中的一個簡單的信息,我在表中。每個文件都有我需要添加到其中的ID。相應的字典具有文件名和id夫婦。在XML中已經有一個空元素,叫做idno [@ type ='TM'],我需要輸入相應的id號。Beautifulsoup xml

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」

我的第二個,可能相關的問題是,當它的工作,我是不是能夠將輸出寫入文件。理想情況下,我想簡單地將其寫回到我正在修改的文件中。

非常感謝您對此的任何建議。

+0

嘗試---從BS4進口BeautifulSoup 進口OS DIR = '文件/' 根= os.path.abspath則(DIR) 對應於100 = { 「00100004」: 「362375」, 「00100005」: 「362376」, 「00100006」: 「362377」, 「00100007」: 「362378」} 給fileName,TM在corresp.iteritems(): 湯= BeautifulSoup(開放(OS。 path.join(root,「fileName」,「。xml」))) tmid = soup.find(「idno」,type =「TM」) tmid.append(tm) print soup – SIslam

回答

0

關於第一個問題:

find()剛剛返回結果。如果find()找不到任何內容,則返回None。結果和None都不是python列表,所以它沒有append()方法。

檢查該文檔: http://www.crummy.com/software/BeautifulSoup/bs4/doc/

+0

Find不會從不返回列表,因此即使發現了某些內容,也會引發異常(不一樣的情況)。 Find_all返回列表或空列表.. –

+0

我看到了,所以這意味着文件中沒有idno?實際上......將這個變化保存到文件中怎麼樣? –

+0

@PietroMariaLiuzzo,anwser已更新,關於第二個問題的追溯信息是什麼? –