python -
标签内的 Beautifulsoup 提取物
问题描述
我有这样的html代码
<td><b>Total : 32</b><br/>Mango : 12<br/>Banana : 4<br/>Grape : 16<br/>Watermelon : 0 </td>
我怎样才能将它提取到这样的变量中?
Total : 32
Mango : 12
Banana : 4
Grape : 16
Watermelon : 0
只需获取数字,名称作为变量
谢谢。
解决方案
尝试:
a = '<td><b>Total : 32</b><br/>Mango : 12<br/>Banana : 4<br/>Grape : 16<br/>Watermelon : 0 </td>'
for i in a.strings:
print(i)
请记住, a 不是字符串,而是 a <class 'bs4.BeautifulSoup'>
。这给出了输出:
Total : 32
Mango : 12
Banana : 4
Grape : 16
Watermelon : 0
这可以存储为字典:
dc = {}
for i in a.strings:
dc[i.split()[0]] = int(i.split()[-1])
这给出了:
{'Total': 32, 'Mango': 12, 'Banana': 4, 'Grape': 16, 'Watermelon': 0}
现在,如果您确定需要像 Total 这样的值为 32 的变量,请尝试(不推荐的方法):
for i in a.strings:
exec(f'{i.split()[0]} = int(i.split()[-1])')
现在打电话给他们:
>>>Total
32
>>>Mango
12
推荐阅读
- java - 通过 Java 访问 Swagger API,而不是手动访问
- google-cloud-platform - Google 管理的 SSL 证书停留在 Provisioning
- javascript - 如何使用 Javascript 或 Jquery 检查复选框值并显示到输入元素?
- php - 无法在不使用 php 和 ajax 调用重新加载页面的情况下提交表单
- indexing - 如何真正处理Redis中的索引并正确实现索引
- python - 当多维形状是列表时,Numba 函数中的 NumPy 零点不起作用
- javascript - 为参数值不在当前范围内的元素创建 onclick
- java - 为什么红移连接中的连接计时错误?
- javascript - 我可以跨域缓存JS文件吗?
- ruby-on-rails - 如何在 Rails 中分离 Admin 和 User 数据库