【问题标题】:Python: Why will this string print but not write to a file?Python:为什么这个字符串会打印但不会写入文件?
【发布时间】:2013-04-22 23:01:34
【问题描述】:

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

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

我尝试在此处调整 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("&lt;html&gt;\n") 我的字符串构造发生了什么?据我所知,我在 minidom 示例中使用的 getText 方法返回一个字符串——这正是你可以写入文件的那种东西..?

【问题讨论】:

  • 什么异常?请发布完整的错误消息,包括堆栈跟踪。
  • 为什么这里有这么多问题只是说“异常”,或者在没有堆栈跟踪的情况下给出消息 - 这是非常有用的调试信息,为什么有人包括它?这让我感到困惑。
  • 我想我们只是认为我们的错误对于专业程序员来说是显而易见的。但你是对的——在学习如何打印堆栈跟踪并发现它只是说NameError: global name 'outputFile' is not defined,我立即能够看到问题所在。学过的知识。 :-)
  • @nicole:专家级的程序员总是犯这样的愚蠢错误;我们唯一真正的优势是,我们做了这么多次,我们知道如何从堆栈跟踪中快速找到问题。 :)
  • 我的印象是很多新手程序员,因为他们并不总是理解堆栈跟踪,所以认为它没有意义并忽略它!

标签: python html xml xml-parsing minidom


【解决方案1】:

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

...
      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
------------------------------------------------------------

看起来有些东西超出了范围!

各位初学者,请注意。

【讨论】:

  • 请注意,如果您不处理异常,它将自动为您打印堆栈跟踪和错误。通常,您应该只捕获您期望出现的确切异常并知道如何处理,否则,让它出现在前面,这样您就可以看到它发生的原因并修复它(通过正确处理异常或停止它永远不会发生)。
猜你喜欢
  • 2014-08-23
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-01
相关资源
最近更新 更多