我想从下表中提取。我在第二次切割后再切6次。总共要提取8个字符串,我需要从下面的示例值61.5,值56.43等。
下面的代码snipplet只给出了第一个值(61.5)。我如何获取剩余的值?
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>
答案 0 :(得分:5)
使用soup.find_all()
获取匹配元素的列表,然后获取每个元素的text
属性:
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']
或者,如果你想要它们作为花车:
data = [float(element.text) for element in soup.find_all("div", "value")]
>>> data
[61.5, 56.43]
答案 1 :(得分:3)
<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>
试试这个:
temp = soup.select('div[class="value"]')
result = []
for i in temp:
result.append(i.get_text())
答案 2 :(得分:0)
您需要在BeautifulSoup中使用find_all()获取所有值。
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)
out=[]
for elem in soup.find_all("div", {"class":"value"}):
out.append(elem.text)