使用 find_elements 时列表没有属性文本

时间:2021-07-13 16:40:27

标签: python selenium

我正在抓取 xbox 网站以获取一些帐户信息。在信息中,我试图抓取某人的姓名和他们的状态,它们属于相同的标签和类别,所以我制作了一个列表来附加这些值中的每一个。但是,该帐户并不总是附有名称,而是始终附有状态,因此我做了一个 if 语句来判断是否有超过 1 个元素被刮掉。但是,它仅在有两个元素时才有效;一个都没有。

status_name = driver.find_elements_by_xpath("//div[contains(@id,'right-side')]/p")

  statusName = []

  if len(status_name) > 1:
    for r in status_name:
      statusName.append(r.text)
    status = statusName[1]
    irlname = statusName[0]
  else:
    status=statusName.text

File "main.py", line 286, in xbox
    statusName.append(status_name.text)
AttributeError: 'list' object has no attribute 'text'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'text'

1 个答案:

答案 0 :(得分:1)

elements (with s) 总是返回 list - 即使是一个元素 - 而且你不必使用 len() - 它总是会迭代列表,而不是字符。

顺便说一句:如果它找不到元素,那么它会给出空列表,你也不需要 len()

status_name = driver.find_elements_by_xpath("//div[contains(@id,'right-side')]/p")

statusName = []

for r in status_name:
    statusName.append(r.text)

或更短

status_name = driver.find_elements_by_xpath("//div[contains(@id,'right-side')]/p")

statusName = [r.text for r in status_name]

编辑:

获取文本后需要 len() - 查看它是否有名称

if len(statusName) > 1:
    status  = statusName[1]
    irlname = statusName[0]
else:
    status  = statusName[0]
    irlname = '???'

最终您可以按照自己的方式编写所有内容,但需要索引。你可以不用列表statusName

status_name = driver.find_elements_by_xpath("//div[contains(@id,'right-side')]/p")

if len(status_name) > 1:
    status  = status_name[1].text
    irlname = status_name[0].text
else:
    status  = status_name[0].text
    irlname = '???'