【发布时间】:2018-12-23 13:57:29
【问题描述】:
我的 Python 能力不是很强,但我正在为我在游戏中参与的公会建立一个站点,并且我正在使用爬虫从另一个站点中提取我们的一些成员数据(是的,我确实收到了允许这样做)。我正在使用漂亮的汤 4 和 python 3.7。我收到错误:
Traceback (most recent call last):
File "/Users/UsersLaptop/Desktop/swgohScraper.py", line 21, in <module>
temp = members[count]
IndexError: list index out of range
我的代码在这里:
from requests import get
from bs4 import BeautifulSoup
# variables
count = 1
# lists to store data
names = []
gp = []
arenaRank = []
url = 'https://swgoh.gg/g/21284/gid-1-800-druidia/'
response = get(url)
soup = BeautifulSoup(response.text, 'html.parser')
type(soup)
members = soup.find_all('tr')
members.sort()
for users in members:
temp = members[count]
name = temp.td.a.strong.text
names.append(name)
count += 1
print(names)
我猜我收到此错误是因为成员中有 50 个成员,但第 50 个为空,如果数据为空,我需要阻止数组附加但是当我尝试放置 if在我的 for 循环下循环,例如:
if users.find('tr') is not None:
它不能解决问题。如果有人能解释如何解决此问题以及该解决方案为何有效,将不胜感激。提前谢谢!
【问题讨论】:
-
PS 即使在查看了类似的问题后,我似乎也无法弄清楚这一点,这非常令人沮丧。
-
索引从 0 开始。
标签: python python-3.x beautifulsoup web-crawler index-error