2011-07-14 29 views
2

這部分代碼解析XML以輸出到網頁上的屏幕。Python CGI腳本(使用XML和mindom)不能提取空數據

XML的
AttributeError: 'NoneType' object has no attribute 'toxml' 
     args = ("'NoneType' object has no attribute 'toxml'",) 

片段被解析:

for counter in range(100): 
    try: 
     for item in BlekkoSearchResultsXML.getElementsByTagName('item'): 
      Blekko_PageTitle = item.getElementsByTagName('title')[counter].firstChild.toxml(encoding="utf-8") 
      Blekko_PageDesc = item.getElementsByTagName('description')[counter].firstChild.toxml(encoding="utf-8") 
      Blekko_DisplayURL = item.getElementsByTagName('guid')[counter].firstChild.toxml(encoding="utf-8") 
      Blekko_URL = item.getElementsByTagName('link')[counter].firstChild.toxml(encoding="utf-8") 
      print "<h2>" + Blekko_PageTitle + "</h2>" 
      print Blekko_PageDesc + "<br />" 
      print Blekko_DisplayURL + "<br />" 
      print Blekko_URL + "<br />" 
    except IndexError: 
     break 

然而,如果遇到一組空的XML標記的,也就是說,如果一個頁面沒有任何頁面標題或描述,並顯示錯誤消息的腳本失敗:

<item> 
     <title>SUSHI FANLISTING</title> 
     <link>http://sushi.perfectdrug.net/</link> 
     <guid>http://sushi.perfectdrug.net/</guid> 
     <description>This is the official...</description> 
     </item> 

我曾嘗試不成功使用一個try/except語句是這樣的:

try: 
    Blekko_PageTitle = item.getElementsByTagName('title')[counter].firstChild.toxml(encoding="utf-8") 
except Blekko_PageTitle = None: 
    Blekko_PageTitle = "No page title provided..." 

任何建議表示讚賞。

回答

0

你在做except錯誤:它捕獲異常對象得到引發。你想

except AttributeError: 

另外,使用條件:

if Blekko_PageTitle = None: 
    ... 
else: 
    ... 
+0

使用的 '除AttributeError的:' 完美。非常感謝。 – user725236