首页 > 解决方案 > 尝试使用正则表达式后,Beautiful Soup 出现错误

问题描述

threads = soup.find_all('tr',id=re.compile('^eventRowId.+'))

for thread in threads:
  t = datetime.datetime.strptime(thread['event_timestamp'],'%Y-%m-%d %H:%M:%S')
  event_times.append(datetime.datetime.strftime(t,'%d-%m'))

到目前为止,上面的脚本运行良好。

for thread in threads:
  performance = thread.find_all('td',title=re.compile('^[IBW].+'))
  print(performance['title'])

在尝试添加这三行之后,再做一次“更深入的搜索”,就会发生错误。我再次进行了搜索,因为我想在“tr”索引之后提取嵌套的“td”

TypeError:列表索引必须是整数或切片,而不是 str

不知何故,性能变量似乎不再是字典。

标签: pythonregexbeautifulsoup

解决方案


的输出find_all()始终是一个列表(即使只有一个元素)。
所以要么迭代performance

for td in performance:
    # do something

或者,如果您确定td每个中只有一个performance,您可以拔出performance[0]

或者,如果您只想要第一个元素(或者如果您确定只有一个元素),请使用find()而不是find_all().


推荐阅读