I am trying to find the problem within this code
Question:
I was trying to run the code below when scraping data from a website:
for match in match_data:
home_team.append(match.find('th', class_='fhome').get_text())
score.append(match.find('th', class_='fscore').get_text())
away_team.append(match.find('th', class_='faway').get_text())
then I got the error message below:
NameError: name ‘home_team’ is not defined
I tried to USE the code below:
for match in match_data:
hometeam = home_team.append(match.find('th', class_='fhome').get_text())
tscore = score.append(match.find('th', class_='fscore').get_text())
awayteam = away_team.append(match.find('th', class_='faway').get_text())
But the error message is still the same as above
Answers:
Make sure to write home_team = []
before the block of code. You have to define home_team
as an empty list before appending to it.
Initialise all three variables as empty lists ([]
or list()
) at the start of your code (before your loop).
Otherwise, you have nothing to append your values to. (append()
is just a method that exists on a list
object. Without storing a list in the variable first, there is nothing to call append()
from.)
home_team = []
score = []
away_team = []
for match in match_data:
home_team.append(match.find('th', class_='fhome').get_text())
score.append(match.find('th', class_='fscore').get_text())
away_team.append(match.find('th', class_='faway').get_text())
I was trying to run the code below when scraping data from a website:
for match in match_data:
home_team.append(match.find('th', class_='fhome').get_text())
score.append(match.find('th', class_='fscore').get_text())
away_team.append(match.find('th', class_='faway').get_text())
then I got the error message below:
NameError: name ‘home_team’ is not defined
I tried to USE the code below:
for match in match_data:
hometeam = home_team.append(match.find('th', class_='fhome').get_text())
tscore = score.append(match.find('th', class_='fscore').get_text())
awayteam = away_team.append(match.find('th', class_='faway').get_text())
But the error message is still the same as above
Make sure to write home_team = []
before the block of code. You have to define home_team
as an empty list before appending to it.
Initialise all three variables as empty lists ([]
or list()
) at the start of your code (before your loop).
Otherwise, you have nothing to append your values to. (append()
is just a method that exists on a list
object. Without storing a list in the variable first, there is nothing to call append()
from.)
home_team = []
score = []
away_team = []
for match in match_data:
home_team.append(match.find('th', class_='fhome').get_text())
score.append(match.find('th', class_='fscore').get_text())
away_team.append(match.find('th', class_='faway').get_text())