Python:为什么这个字符串会打印但不能写入文件?

时间:2013-04-22 23:01:34

标签: python html xml xml-parsing minidom

我是Python的新手,并且正在开发一个将XML文件更改为HTML的实用程序。 XML来自对request = urllib2.Request(url)的调用,我在代码中先生成自定义网址,然后设置response = urllib2.urlopen(request),最后设置xml_response = response.read()。据我所知,这很好用。

我的麻烦在于解析响应。对于初学者,这是我得到的XML结构的部分示例:

enter image description here

我尝试在此处使用minidom教程中的幻灯片示例来解析我的XML(顺便说一下,这是ebay搜索结果):http://docs.python.org/2/library/xml.dom.minidom.html

到目前为止,我的代码看起来像这样,尝试使用try块来尝试诊断问题:

doc = minidom.parseString(xml_response)

  #Extract relevant information and prepare it for HTML formatting.
  try: 
    handleDocument(doc)
  except:
    print "Failed to handle document!" 

def getText(nodelist):  #taken straight from slideshow example 
  rc = []
  for node in nodelist:
    if node.nodeType == node.TEXT_NODE:
      print "A TEXT NODE!" 
      rc.append(node.data)
  return ''.join(rc)       #this is a string, right?

def handleDocument(doc): 
  outputFile = open("EbaySearchResults.html", "w")
  outputFile.write("<html>\n")
  outputFile.write("<body>\n")
  try:
    items = doc.getElementsByTagName("item") 
  except:
    "Failed to get elements by tag name." 
  handleItems(items)
  outputFile.write("</html>\n")
  outputFile.write("</body>\n") 

def handleItems(items):
  for item in items:    
    title = item.getElementsByTagName("title")[0] #there should be only one title

    print "<h2>%s</h2>" % getText(title.childNodes) #this works fine!

    try: #none of these things work!
      outputFile.write("<h2>%s</h2>" % getText(title.childNodes))

      #outputFile.write("<h2>" + getText(title.childNodes) + "</h2>")

      #str = getText(title.childNodes) 
      #outputFIle.write(string(str)) 
      #outputFile.write(getText(title.childNodes))  

    except:
      print "FAIL"  

我不明白为什么正确的标题文本会打印到控制台但会引发异常并且对输出文件不起作用。写这样的普通字符串工作正常:outputFile.write("<html>\n")我的字符串结构发生了什么?据我所知,我在minidom示例中使用的getText方法返回一个字符串 - 这就是你可以写入文件的那种东西..?

1 个答案:

答案 0 :(得分:0)

如果我打印实际的堆栈跟踪......

...
      except:
        print "Exception when trying to write to file:"
        print '-'*60
        traceback.print_exc(file=sys.stdout)
        print '-'*60
        traceback.print_tb(sys.last_traceback)
...

......我会立即看到问题:

------------------------------------------------------------
Traceback (most recent call last):
  File "tohtml.py", line 85, in handleItems
    outputFile.write(getText(title.childNodes))
NameError: global name 'outputFile' is not defined
------------------------------------------------------------

看起来有些事情超出了范围!

初学者,请注意。

相关问题