【问题标题】:Web Crawler Array error: "list index out of range"网络爬虫数组错误:“列表索引超出范围”
【发布时间】: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


【解决方案1】:

这将完成您尝试从代码中获取的工作,即尝试获取可以从代码中推断出的名称

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.content, 'html.parser')

for users in soup.findAll('strong'):
    if users.text.strip().encode("utf-8")!= '':
        names.append(users.text.strip().encode("utf-8"))



print(names)

【讨论】:

  • 你是最接近解决我问题的人,也是唯一一个没有给出抛出错误代码的人,所以谢谢你!这是打印这样的内容: [u'Note', u'', u'GP'] 我很困惑,因为不应该删除 u 和 ' '?
  • 这只是编码部分。我已经编辑了相同的答案!
  • 添加了忽略任何空数据''的代码。
  • 谢谢!!您能解释一下为什么需要 .encode 部分吗?你是唯一一个理解我的问题并能够解决它的人。我真的很难理解 .encode("utf-8") 的作用。
  • 请参阅此stackoverflow.com/questions/2241348/… 和一个友好的建议,在提出问题之前仔细阅读。我知道学习新事物可能具有挑战性,但您会逐渐了解它,只需尝试/阅读每个角落和关于它的角落。它是一个很好的做法,肯定会帮助你成长!快乐的编码和学习!
【解决方案2】:

当您使用for in 循环时,您不需要count 变量。

for users in members:
    name = users.td.a.strong.text
    names.append(name)

【讨论】:

  • 发生这种情况时会出现“AttributeError: 'NoneType' object has no attribute 'a'”。我意识到我不需要 count 变量,但我似乎让它在更好的状态下工作。
【解决方案3】:

首先更改count=0,因为成员索引从0开始

【讨论】:

  • 我意识到索引不是从 0 开始,但列表的开头不是我需要的项目,所以我跳过它。这并不能解决问题。
【解决方案4】:

你的代码应该是这样的:

from requests import get
from bs4 import BeautifulSoup    
# 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:
    name = users.td.a.strong.text
    names.append(name)


print(names)

您可以将count 更改为0,因为python 索引从0 开始,但最好还是直接从迭代器users 执行它

【讨论】:

  • 此代码不起作用。我意识到python索引从0开始。我最初也写了这段代码,但是这段代码出现了一个错误,说“NoneType”对象没有属性a。它显然是在抓取没有锚标签的东西,所以我不得不省略 50 个元素中的一个,但我不知道怎么做。我相信可能的 50 个成员中有 49 个成员,所以我需要 49 个成员,然后用一个空字符串填充一个空位置。