2013-05-29 47 views
0

我試圖從XML文檔中提取IP地址,這裏是相關的代碼。使用re.findall時出現TypeError

def traverseNode(node): 
    output = node.find(****) 
    if output is not None: 
     ips = re.findall(r'[0-9]+(?:\.[0-9]+){3}', output) 
     for ip in ips: 
      print ip 
    for child in node.getchildren(): 
     traverseNode(child) 

此代碼返回錯誤類型錯誤:預期的字符串或緩衝區 上是什麼導致了這種任何想法?預先感謝您的幫助。

+0

什麼是'output'的類型?我通常會猜測它是另一個'node'或其他東西,而不是一個字符串或緩衝區... – mgilson

+0

'find'返回節點對象。你可能想在'output.text'或'output.attrib'或類似的東西中搜索IP – RedBaron

+0

是的,事實證明我需要將輸出設置爲nod.find().text。 – avorum

回答

0

確保第二個參數re.findall(pattern,arg)是一個字符串。您可以使用str(arg)來確保將字符串放入re.findall中。

0

因此,解決方案是將該行更改爲: 輸出= node.find( '* *')文本

+0

如果沒有找到匹配,它會拋出一個'AttributeError:NoneType對象沒有屬性文本'的錯誤。繼續按原樣做,但是當使用're' do'ips = re.findall(r'[0-9] +(?:\。[0-9] +){3}',output.text)時, ' – RedBaron

相關問題