0

我是 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

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

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

4

1 回答 1

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

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

初学者,请注意。

于 2013-04-23T00:23:10.903 回答