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

2024-10-04 09:19:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,正在开发一个将XML文件更改为HTML的实用程序。XML来自于对request = urllib2.Request(url)的调用,我在代码的前面生成了自定义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方法返回一个字符串——这正是您可以写入文件的那种东西。。?在


Tags: nodedoctitleresponsehtmlitemsh2xml
1条回答
网友
1楼 · 发布于 2024-10-04 09:19:46

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

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

……我会立刻发现问题:

^{pr2}$

好像有什么东西超出了范围!在

各位初学者,请注意。在

相关问题 更多 >