从td,跨度和风格中提取的甜蜜汤


<td><span data-tooltip="some text" class="tooltip button is-success is-small" style="cursor: default;">
23 - 1 - 13 (<span class="is-danger" style="font-weight: 700;">1.77</span>)

我正在寻找那些数字 23 - 1 - 13。如何提取它们?我在Python中使用BeautifulSoup。

您需要在span而不是td上进行查找,因为该元素包含您要搜索的类:

soup.find_all('span', class_="tooltip button is-success is-small")

您也可以使用soup.span.textspan标记中查找文本。然后一些标准的Python将其拆分并转换为数字。如果有多个元素,可以按如下方式完成:

from bs4 import BeautifulSoup
html = """
<td><span data-tooltip="some text" class="tooltip button is-success is-small" style="cursor: default;">23 - 1 - 13 (<span class="is-danger"style="font-weight: 700;">1.77</span>)</td>
<td><span data-tooltip="some text" class="tooltip button is-success is-small" style="cursor: default;">23 - 1 - 13 (<span class="is-danger"style="font-weight: 700;">1.77</span>)</td>
<td><span data-tooltip="some text" class="tooltip button is-success is-small" style="cursor: default;">23 - 1 - 13 (<span class="is-danger"style="font-weight: 700;">1.77</span>)</td>
"""
soup = BeautifulSoup(html, "html.parser")
for span in soup.find_all('span', class_='tooltip button is-success is-small'):
numbers = [int(v) for v in span.text.strip().split(' ')[:-1] if v != '-']
print(numbers)

这将为您提供列表中的三个数字,如下所示:

[23, 1, 13]    
[23, 1, 13]    
[23, 1, 13]    

最新更新