我正在尝试从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'
答案 0 :(得分:1)
xml.dom.minidom.parse
不是文件类对象,而是bytes
或str
,如文档中所述:
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