首页 > 解决方案 >
标签内的 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

只需获取数字,名称作为变量

谢谢。

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


尝试:

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

推荐阅读