【发布时间】:2020-01-28 00:21:04
【问题描述】:
到目前为止,我有以下代码,我将其全部包含在内以防万一
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]
我得到的错误是
---------------------------------------------------------------------------
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
如果我在list(todays_games.children) 和Len(list(todays_games.children)) 上执行type(),我会得到“列表”和长度,在这个特殊的日子里,这个特殊情况恰好是6,所以我不明白为什么我会得到这个错误。有什么想法吗?
【问题讨论】:
-
这能回答你的问题吗? Looping over a list in Python
-
for games in len(list(todays_games.children)):尝试遍历len返回的 integer。您只需要for game in todays_games.children:,您很少需要在 Python 中循环索引,for循环是“for each”循环,即基于迭代器的 for 循环。 -
我不太了解 Beautiful Soup,但我认为 list() 是我试图遍历的 .children 列表的原因。
标签: python beautifulsoup python-requests