bytes-like object is required, not 'str'

0

I'm trying to run this code:

import time

import urllib.request

from urllib.request import urlopen

ibov = ['BBAS3.SA', 'PETR4.SA']

def yahooKeyStats(stock):

try:
    sourceCode = urllib.request.urlopen ('https://finance.yahoo.com/quote/.../key-statistics?p=' +stock).read()
    pl = sourceCode.split('Preço/Livro </td><td class="Fz(s) Fw(500) Ta(end)">')[1].split('</td>')[0]
    print ("preço livro:", pl)

except Exception as e:
       print (e)

I've checked all the possibilities and can not fix it. Sorry for the question, which may be silly, but I'm starting and I have questions.

    
asked by anonymous 31.12.2017 / 07:50

1 answer

1

Your problem is very simple. If you check the urlopen returns an object of type "bytes" convert "sourceCode" to string first:

sourceCode = str(sourceCode)
pl = sourceCode.split('Preço/Livro </td><td class="Fz(s) Fw(500) Ta(end)">')[1].split('</td>')[0]
print ("preço livro:", pl)

Another thing and what you're doing to extract the stock price is a bit confusing I recommend you use BeautifulSoup to extract information from an HTML document.

    
31.12.2017 / 21:15