is there a way to convert the data I have web scraped into a pandas DataFrame?
Scraped data is Stock fundamentals data Ex. abt: 2.71 6.00 abt = stock ticker, 2.71 = Price to Book ratio and 6.00 = PEG ratio
I tried declaring a variable with an empty dataframe and used .append() function but no luck
Im guessing the data should be converted somehow before it can be passed to a dataframe, but Im now aware on how to do it.
Code redone with the suggestion from the comments, now the dataframe is coming out empty???
import time
import urllib.request
import urllib.parse
import pandas as pd
sp500short = ['a', 'aa', 'aapl', 'abbv', 'abc', 'abt', 'ace', 'aci', 'acn', 'act', 'adbe', 'adi', 'adm', 'adp']
#stock = 'a'
data = []
color_list = ['<span style="color:#aa0000;">', '<span style="color:#008800;">']
color_close = '</span>'
def finvizPBStats(stock):
try:
sourceCode = urllib.request.urlopen('http://finviz.com/quote.ashx?t='+stock).read()
sourceCodeString = sourceCode.decode()
pbr = sourceCodeString.split('P/B</td><td width="8%" class="snapshot-td2" align="left"><b>')[1].split('</b></td>')[0]
for color in color_list:
if color in pbr:
pbr = pbr.split(color)[1].split(color_close)[0]
pbr = float(pbr)
except Exception as e:
if Exception:
pass
return
def finvizPEGStats(stock):
try:
sourceCode = urllib.request.urlopen('http://finviz.com/quote.ashx?t='+stock).read()
sourceCodeString = sourceCode.decode()
PEG = sourceCodeString.split('PEG</td><td width="8%" class="snapshot-td2" align="left"><b>')[1].split('</b></td>')[0]
for color in color_list:
if color in PEG:
PEG = PEG.split(color)[1].split(color_close)[0]
PEG = float(PEG)
except Exception as e:
if Exception:
pass
return
for stock in sp500short:
pbr = finvizPBStats(stock)
PEG = finvizPEGStats(stock)
data.append([pbr, PEG])
df = pd.DataFrame(index=sp500short, columns=['pbr', 'PEG'])
print(df)


df(input_data).return pbr, PEG. Also, with how your functions are structured, this may raise errors unless you initialize pbr and PEG. For example you could try addingpbr, PEG = 0, 0in the functions before the try / except statements.