python - 尝试使用正则表达式后,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
不知何故,性能变量似乎不再是字典。
解决方案
的输出find_all()
始终是一个列表(即使只有一个元素)。
所以要么迭代performance
:
for td in performance:
# do something
或者,如果您确定td
每个中只有一个performance
,您可以拔出performance[0]
。
或者,如果您只想要第一个元素(或者如果您确定只有一个元素),请使用find()
而不是find_all()
.
推荐阅读
- python - 编写查找数字数组中元素索引的函数
- angular - 如何创建自定义响应式表单元素?
- reactjs - 使用 Bulma.css 在 React.js 中每 3 个列元素添加新的列容器
- xamarin.forms - 如何将详细信息页面变成母版页?
- python-3.x - Python - 无法将发布请求发送到登录表单
- common-lisp - Read file by line and wait for keyboard input to read next line
- ninja - 确定哪些目标在忍者中一次全部失败
- php - ifconfig 并在将 Magento 从 2.1.2 更新到 2.2.7 后无法工作
- build - 在 Sublime Text 构建系统中使用自定义变量
- konvajs - KonvaJS - 响应阶段和完整的 toDataURL