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

Asked By: obabtd

||

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.

Answered By: Fahd Seddik

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())
Answered By: MatBailie
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.