我看过一些的例子在这里,但我这样一个新手,我不明白他们中的一些和其他人似乎不工作(可能是因为我是个新手,但...字节到字符串或字符串到字节?
import urllib.request
import re
Symbols = ['aapl', 'spy' , 'goog' , 'nflx']
i = 0
while i < len(Symbols):
Yahoo='http://finance.yahoo.com/q?s=' + Symbols[i]
htmlfile = urllib.request.urlopen(Yahoo)
htmltext = htmlfile.read()
string = Symbols[i]
symbol = string.encode('utf-8')
pattern= re.compile(b'<span id="yfs_l84_'+ symbol +'">(.+?)</span>')
price= re.findall(pattern, htmltext)
print('The price of' + str(Symbols[i]) + ' is ' + str(price))
i+=1
这不会因为re.compile
声明我试图来连接海峡和字节我需要将字符串转换为字节,这样我以后可以遍历符号列表和刮最新股价工作。
来自雅虎财经
我有一种感觉,我的语法出现了问题d例子和python文档有一个'编码'的参数,我认为它是'utf-8'字符串,但我不知道。
有人可以帮助我吗?
编辑:我在这里使用字节,因为这是它的唯一工作方式,如果我没有(我正在使用3.3),我得到一个错误将其更改为字节。
的错误是这样的:
Traceback (most recent call last):
File "C:\Users\Deaven And Teigan\Documents\Python Projects\YahooFinance.py", line 14, in <module>
pattern= re.compile(b'<span id="yfs_l84_'+ symbol +'">(.+?)</span>')
TypeError: can't concat bytes to str
你为什么要用字节串来创建正则表达式?另外,请发布堆栈跟踪和异常与您的问题。 – 2013-05-12 18:25:09
@Lattyware,TypeError:不能在类似字节的对象上使用字符串模式 – 2013-05-12 18:33:23