使用BeautifulSoup从标签中提取字符串 [英] Extract string from tag with BeautifulSoup
本文介绍了使用BeautifulSoup从标签中提取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从下表中提取内容.我在第二个<td>
之后剪切了它,之后又剪切了六个.需要提取所有八个字符串,例如在下面的示例中,我想要值61.5
,56.43
等
I am trying to extract from below table. I cut it after the second <td>
, with six more to follow. All eight strings need to be extracted, e.g. in the example below I would want the values 61.5
, 56.43
, etc.
下面的代码仅给我第一个值61.5
.我如何获得剩余的价值?
The code below only gives me the first value, 61.5
. How can I get the remaining values?
soup.find("div", {"class":"value"}).text
<td class="flow">
<div class="heading" style="min-height: 63px;">Dornum</div>
<div class="data"><div class="value">61.5</div> MSm<sup>3</sup>/d</div>
</td>
<td class="flow">
<div class="heading" style="min-height: 63px;">Emden EMS</div>
<div class="data"><div class="value">56.43</div> MSm<sup>3</sup>/d</div>
</td>
推荐答案
使用soup.find_all()
获取匹配元素的列表,然后获取每个元素的text
属性:
Use soup.find_all()
to obtain a list of matching elements, then grab the text
attribute for each element:
from bs4 import BeautifulSoup
html = '''<td class="flow">
<div class="heading" style="min-height: 63px;">Dornum</div>
<div class="data"><div class="value">61.5</div> MSm<sup>3</sup>/d</div>
</td>
<td class="flow">
<div class="heading" style="min-height: 63px;">Emden EMS</div>
<div class="data"><div class="value">56.43</div> MSm<sup>3</sup>/d</div>
</td>'''
soup = BeautifulSoup(html)
data = [element.text for element in soup.find_all("div", "value")]
>>> data
[u'61.5', u'56.43']
或者,如果您希望它们为浮点数:
Or, if you want them as floats:
data = [float(element.text) for element in soup.find_all("div", "value")]
>>> data
[61.5, 56.43]
这篇关于使用BeautifulSoup从标签中提取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文