0

So far I have the following code, I'm including all of it in case it helps

import requests
from bs4 import BeautifulSoup

URL = 'https://projects.fivethirtyeight.com/2020-nba-predictions/games/'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')

todays_games = soup.find('div', class_="games-section extra-space-0")

stats = []
for games in len(list(todays_games.children)):
    game = list(todays_games.children)[games]

and the error I am getting is

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-39f21f5da0b0> in <module>
      1 #This is the main new feature of this version. A for loop to perform the operation for all the games of that day
      2 stats = []
----> 3 for games in len(list(todays_games.children)):
      4     game = list(todays_games.children)[games]
      5     game_body = game.body

TypeError: 'int' object is not iterable

If I do type() on list(todays_games.children) and Len(list(todays_games.children)) I get "list" and the length, which happens to be 6 for this particular case on this particular day, So I don't understand why I am getting this error. Any Ideas?

jon
  • 239
  • 1
  • 4
  • 17
  • 1
    Does this answer your question? [Looping over a list in Python](https://stackoverflow.com/questions/9138112/looping-over-a-list-in-python) – Mike Scotty Jan 28 '20 at 00:24
  • 2
    `for games in len(list(todays_games.children)):` tries to loop over the *integer* returned by `len`. You just want `for game in todays_games.children:` you rarely need to loop over indices in Python, the `for` loop is a "for each" loop, i.e. an iterator based for-loop. – juanpa.arrivillaga Jan 28 '20 at 00:25
  • I don't know Beautiful soup that well, I though list() is what makes the list out of the .children that I was trying to iterate through. – jon Jan 28 '20 at 00:33

1 Answers1

2

len(list(todays_games.children)) evaluates to an integer - 5, 6, etc. You can't iterate directly over an integer with a for loop.

You can use the built-in function range to loop a set number of times if you'd need, but you should iterator directly over todays_games.children.

A big part of Python is that it simplifies iterator usage. Instead of using indices to access things like an array, (asking for the 5th element, etc) you can directly access the element with the for loop.

for game in todays_games.children:
    curr_game  = game.body
    do_something_else(curr_game)

compare this to

for i in range(len(todays_games.children)):
    curr_game = todays_games.children[i].body
    do_something_else(curr_game)
```.
bbbbbb
  • 106
  • 6
  • Thank you, this went above and beyond what I was looking for! The code does look a little cleaner now. – jon Jan 28 '20 at 00:50