TypeError:Python中预期的字符串或类似字节的对象

时间:2018-11-16 18:00:52

标签: python

我目前正在休息。 TypeError是什么?如何解决?规范中需要进行哪些必要的修改?

from urllib.request import urlretrieve

stoxxeu600_url = urllib.request.urlretrieve('https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt')
vstoxx_url = urllib.request.urlretrieve('https://www.stoxx.com/document/Indices/Current/HistoricalData/h_vstoxx.txt')

data_folder = 'data/' #Save file to local target destination.
stoxxeu600_filepath = data_folder + "stoxxeu600.txt"
vstoxx_filepath = data_folder + "vstoxx.txt"
urlretrieve(stoxxeu600_url,stoxxeu600_filepath)

这是输出:

File "/home/aryabhatta/anaconda3/lib/python3.6/urllib/parse.py", line 938, in splittype
match = _typeprog.match(url)

TypeError: expected string or bytes-like object

2 个答案:

答案 0 :(得分:0)

urlretrieve希望将字符串作为其第一个参数。因此stoxxeu600_url应该是字符串。

from urllib.request import urlretrieve

stoxxeu600_url = 'https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt'
data_folder = 'data/' #Save file to local target destination.
stoxxeu600_filepath = data_folder + "stoxxeu600.txt"
urlretrieve(stoxxeu600_url, stoxxeu600_filepath)

答案 1 :(得分:0)

您可以从urlretrieve()的文档中看到,该方法返回一个元组(filename, headers)

在代码中,您首先调用urlretrieve()并将其存储到stoxxeu600_url

stoxxeu600_url = urllib.request.urlretrieve('https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt')

stoxxeu600_url现在有(filename, headers)返回的urlretrieve()

然后,再次使用urlretrieve()调用stoxxeu600_url,它是方法期望的元组,而不是str / byte对象。从而导致TypeError。

urlretrieve(stoxxeu600_url,stoxxeu600_filepath)

要修复此问题,只需将stoxxeu600_url设置为url,然后调用该方法。

from urllib.request import urlretrieve

stoxxeu600_url = 'https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt'
stoxxeu600_filepath = "stoxxeu600.txt"
urlretrieve(stoxxeu600_url, filename=stoxxeu600_filepath)