[英]Beautifulsoup extract inside <br> tag
我有這樣的 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 不是字符串而是<class 'bs4.BeautifulSoup'>
。 這給出了 output:
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
您還可以使用 FOP 方法(假設您已經將 soup 創建為soup
:
map(lambda br: print(br.text), soup.find_all('br'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.