gpt4 book ai didi

python - 向 urllib.request.read 传递字符串但获取字节属性错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:21:20 25 4
gpt4 key购买 nike

我正在尝试从雅虎财经 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'

最佳答案

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

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

Return a Document from the given input. filename_or_file may be either a file name, or a file-like object.

所以你只需要这样做:

dom = parse(xml)

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

关于python - 向 urllib.request.read 传递字符串但获取字节属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com