传递一个字符串但得到字节属性错误到urllib.request.read

时间:2014-06-06 15:45:15

标签: python xml urllib

我正在尝试从Yahoo finance API读取XML文件。到目前为止,我已尝试过以下方法:

 from xml.dom.minidom import parse
 #Start Get Employees
        xml = urllib.request.urlopen('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.stocks%20where%20symbol%3D%22wfc%22&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
        dom = parse(xml.read())
        numemployees = dom.getElementsByTagName('FullTimeEmployees')
        numemployees = name[0].firstChild.nodeValue
 #End Get Employees

然而,这引起了例外:

AttributeError: 'bytes' object has no attribute 'read'

我认为这是因为如果它不识别字符串,则假定我传递了一个字节模式。但是,我正在传递一个字符串,所以我不知道这里的问题是什么。

完整堆栈跟踪:

Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
    return self.func(*args)
  File "C:\Users\kylec\Desktop\dm\Mail Server Finder\mailserverfinder.py", line 25, in getServers
    dom = parse(xml.read())
  File "C:\Python34\lib\xml\dom\minidom.py", line 1960, in parse
    return expatbuilder.parse(file)
  File "C:\Python34\lib\xml\dom\expatbuilder.py", line 913, in parse
    result = builder.parseFile(file)
  File "C:\Python34\lib\xml\dom\expatbuilder.py", line 204, in parseFile
    buffer = file.read(16*1024)
AttributeError: 'bytes' object has no attribute 'read'

2 个答案:

答案 0 :(得分:1)

xml.dom.minidom.parse不是文件类对象,而是bytesstr,如文档中所述:

  

xml.dom.minidom.parse(filename_or_file [,parser [,bufsize]])

     

从给定输入中返回文档。 filename_or_file可以是     文件名或文件类对象。

所以你只需要这样做:

dom = parse(xml)

因为http.client.HTTPResponse返回的urlopen对象与文件类似。

答案 1 :(得分:0)

凯尔,对不起,但你的榜样不够明确。我认为这是你期望的。

from xml.dom.minidom import parseString

employees = urllib.urlopen('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.stocks%20where%20symbol%3D%22wfc%22&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys').read()
dom = parseString(employees)
numemployees = dom.getElementsByTagName('FullTimeEmployees')
numemployees = numeemployees[0].firstChild.nodeValue