I'm trying to write a basic python program that takes the price to book ratio from yahoo finance's website. However, i'm getting an error:
failed in the main loop a bytes-like object is required, not 'str'
I've tried using encoding with this line:
sourceCode.read().decode('utf-8')
However this leads to another error of:
failed in the main loop 'bytes' object has no attribute 'read'
Any Help would be appreciated. The full code is below:
import time
import urllib.request
from urllib.request import urlopen
stocks = ['aapl', 'fb', 'goog']
def keyStats(stock):
try:
sourceCode = urllib.request.urlopen('https://finance.yahoo.com/quote/' + stock + '/key-statistics?p=' + stock).read()
ptb = sourceCode.split('Price/Book</span><!-- react-text: 58 --> <!-- /react-text --><!-- react-text: 59 -->(mrq)<!-- /react-text --><sup aria-label="KS_HELP_SUP_undefined" data-reactid="60"></sup></td><td class="Fz(s) Fw(500) Ta(end)" data-reactid="61">')[1].split('</td>')[0]
print ('Price to Book Ratio: ', stock, ptb)
except (Exception) as e:
print ('failed in the main loop', e)
for newStock in stocks:
keyStats(newStock)
time.sleep(1)