I am trying to use beautiful soup to extract data from espn.
However I have trouble assigning values to the correct column. Certain values I am extract are shifting my data into different columns.
When I print the data to excel, values are not aligning correctly. Are their ways to assign values to correct columns?
Any help would be appreciated.
Code:
from bs4 import BeautifulSoup
import pandas as pd
import requests
url = 'https://www.espn.com/nba/player/gamelog/_/id/3012/kyle-lowry'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
columns=[
'Date',
'OPP',
'Result',
'MIN',
'FG',
'FG%',
'3PT',
'3P%',
'FT',
'FT%',
'REB',
'AST',
'BLK',
'STL',
'PF',
'TO',
'PTS',
]
# create dataframe
d1 = pd.DataFrame(columns=columns)
full = []
for data in soup.find_all('td', attrs = {'class': 'Table__TD'}):
val = data.get_text()
full.append(val)
# seperate full list into sub-lists with 17 elements
rows = [full[i: i+17] for i in range(0, len(full), 17)]
# append list of lists structure to dataframe
d1 = d1.append(pd.DataFrame(rows, columns=d1.columns))
print(d1)
d1.to_csv('C:\\Users\\Jonathan\\test7.csv')
