【问题标题】:Python 'int' object is not iterable when using len on a list from beautifulsoup在 beautifulsoup 的列表中使用 len 时,Python 'int' 对象不可迭代
【发布时间】: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


【解决方案1】:

len(list(todays_games.children)) 计算结果为整数 - 5、6 等。您不能使用 for 循环直接迭代整数。

如果需要,您可以使用内置函数 range 循环一定次数,但您应该直接在 todays_games.children 上进行迭代。

Python 的一个重要部分是它简化了迭代器的使用。您可以使用 for 循环直接访问元素,而不是使用索引来访问数组之类的东西(请求第 5 个元素等)。

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

比较一下

for i in range(len(todays_games.children)):
    curr_game = todays_games.children[i].body
    do_something_else(curr_game)
```.

【讨论】:

  • 谢谢,这超出了我的预期!代码现在看起来确实更简洁了。
猜你喜欢
  • 2023-03-07
  • 2019-12-03
  • 2021-07-05
  • 2014-11-04
  • 2015-04-14
  • 2022-07-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-26
相关资源
最近更新 更多