Brad Cunningham Brad Cunningham - 11 months ago 121
Python Question

Python - Looping over a DICT and getting a TraceBack Error

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


Code:

for player in players:
name = player[0].text.strip()
print(name)


I have looked all over Google and Stackoverflow and found a few If statements to try, but still not luck.

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download