I have created a DICT with BeautifulSoup with a length of 42. I am trying to extract the text from the tag and I know that some at the end are blank. When I enter player[42].text it returns a blank from REPL, but when I call it in a loop I get:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/Brad/anaconda/lib/python3.6/site-packages/bs4/element.py", line 997, in __getitem__
return self.attrs[key]
KeyError: 0
for player in players:
name = player[0].text.strip()
print(name)
The for loop iterates over the items in players
assigning to player
each item in turn. When trying to index that with player[0]
BeautifulSoup treats it as an attribute lookup using the attribute name 0
. There is no attribute named 0
in the player tag so the lookup fails and KeyError
is raised.
You should loop like this:
for player in players:
name = player.text.strip()
print(name)