TypeError:无法将字节连接到str

时间:2013-12-28 11:59:01

标签: python regex

我正在尝试将一个示例作为教程。此代码的目的是读取URL,为公司列表提取股票值并打印该值。我有什么,试图拼凑一些建议其他帖子,原始代码(Python 3)是:

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()
    pattern= re.compile(b'<span id="yfs_l84_'+ Symbols[i] +'">(.+?)</span>')
    price= re.findall(pattern, htmltext)
    print('The price of' + (Symbols[i]) + ' is ' + str(price))
    i+=1

我知道html.read()的输出是以字节为单位的,所以我需要将我的正则表达式模式转换为'bytes'(使用'b')我的错误信息是:

Traceback (most recent call last):
  File "C:/Users/User/Documents/Raspberry Pi/Python/web scraper/web_scraper_v2.1.py", line 11, in
    price= re.findall(pattern, htmltext)
  File "C:\Python33\lib\re.py", line 201, in findall
    return _compile(pattern, flags).findall(string)
TypeError: can't use a string pattern on a bytes-like object

我怀疑这与语法有关,但无法解决 有什么建议吗?

1 个答案:

答案 0 :(得分:2)

你走了:

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()
    # Changed the string below so that we can resolve the problems with putting the
    # symbol value in the right place. str.format has been used instead
    # Also, the string has been made into a normal string again
    pattern = re.compile('<span id="yfs_l84_{symbol}">(.+?)</span>'.format(symbol=Symbols[i]))
    # Here htmltext is turned into a string so that we can compare, without the type-error
    price = re.findall(pattern, str(htmltext))
    print('The price of' + (Symbols[i]) + ' is ' + str(price))
    i += 1