我目前正在编写一个程序,从csv文件的第一列中提取字符串列表,然后将其存储在.txt文件中,最后使用urllib解析Yahoo Finance以获取与每个字符串对应的价格。然而,我一直得到错误:
TypeError: 'str' does not support the buffer interface.
import csv
import urllib.request
completeList = open('complete.txt', 'r+')
def ReadNasdaq():
with open('NASDAQ_companylist.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for column in spamreader:
completeList.write(column[0]+'n')
print(column[0]," - ",column[1])
ReadNasdaq()
def ParsePrice():
for line in completeList:
yahooFinance = urllib.request.urlopen("http://finance.yahoo.com/q?s="+line).read()
price = yahooFinance.split('<span id="yfs_l84_'+line.lower()+'">' )[1].split("</span>")[0]
print(line, " - ", price)
ParsePrice()
错误在行:
price = yahooFinance.split('<span id="yfs_l84_'+line.lower()+'">' )[1].split("</span>")[0]
我知道我必须将字符串转换为Unicode或二进制,但知道我该怎么做吗?
某些东西期望字节字符串,但您给出Unicode字符串。
在这种情况下,您正在尝试将从read()返回的二进制数据与Unicode字符串分开。
试试这个:
price = yahooFinance.split(b'<span id="yfs_l84_'+line.lower()+b'">' )[1].split(b"</span>")[0]