【问题标题】:Beautiful Soup getting error after trying to use regular expression尝试使用正则表达式后,Beautiful Soup 出现错误
【发布时间】:2020-05-31 07:52:42
【问题描述】:
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

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

【问题讨论】:

标签: python regex beautifulsoup


【解决方案1】:

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

for td in performance:
    # do something

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

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

【讨论】:

  • 您好 Andrew,感谢您的回答,我想提取性能中的属性。但我不能这样做。不过,我可以在我的第一次迭代中使用变量线程来做到这一点。
  • 哦不,它确实有效!要提取属性,请执行以下操作:performance[0]['title'] 而不是 performance['title']
  • 我很高兴它有效@Wiley。如果您的问题得到了满意的答案,请通过单击该答案左侧的复选标记将其标记为已接受。这会让其他人知道您还没有在这个问题上寻求帮助。
猜你喜欢
  • 2018-08-28
  • 2012-11-27
  • 2015-09-04
  • 2019-08-28
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
  • 2023-04-06
  • 2018-07-13
相关资源
最近更新 更多