[英]Beautifulsoup extract inside <br> tag
I have html code like this我有这样的 html 代码
<td><b>Total : 32</b><br/>Mango : 12<br/>Banana : 4<br/>Grape : 16<br/>Watermelon : 0 </td>
How can i extract it to variable like this?我怎样才能将它提取到这样的变量中?
Total : 32
Mango : 12
Banana : 4
Grape : 16
Watermelon : 0
Just get the number, the name as variable只需获取数字,名称作为变量
Thanks.谢谢。
Try:尝试:
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)
Remember, a is not a string but a <class 'bs4.BeautifulSoup'>
.请记住, a 不是字符串而是<class 'bs4.BeautifulSoup'>
。 this gives the output:这给出了 output:
Total : 32
Mango : 12
Banana : 4
Grape : 16
Watermelon : 0
This can be stored as a dictionary:这可以存储为字典:
dc = {}
for i in a.strings:
dc[i.split()[0]] = int(i.split()[-1])
this gives:这给出:
{'Total': 32, 'Mango': 12, 'Banana': 4, 'Grape': 16, 'Watermelon': 0}
Now if you are sure that you need variables like Total which has the value 32, try (not recommended method):现在,如果您确定需要像 Total 这样值为 32 的变量,请尝试(不推荐的方法):
for i in a.strings:
exec(f'{i.split()[0]} = int(i.split()[-1])')
Now call them:现在打电话给他们:
>>>Total
32
>>>Mango
12
You can also use FOP approach (assuming that you've already soup created as soup
:您还可以使用 FOP 方法(假设您已经将 soup 创建为soup
:
map(lambda br: print(br.text), soup.find_all('br'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.