首页 > 解决方案 > 从 BeautifulSoup 的表中排除跨度类

问题描述

以下代码从网页上的特定表格中提取数据:

import requests
from bs4 import BeautifulSoup
url="XYZ"
sector_response=requests.get(url)
soup=BeautifulSoup(sector_response.content,'lxml')

#Find the desired table
table=soup.find('table',attrs={'class': 'snapshot-data-tbl'})
headings = [th.get_text() for th in table.find("tr").find_all("th")]
for row in table.find_all("tr"):
    dataset = list(zip(headings, (td.get_text() for td in row.find_all("td"))))  
#Exclude the 'Weighting Recommendations' tuple
new_dataset=[i for i in dataset if i[0]!='Weighting Recommendations']
for item in new_dataset:
    print(item)

但是,表主体中的每个单元格都包含一个我不需要的时间戳跨度类。我怎样才能排除这些?

例如:

<td>
<span class="negative">-0.39%</span>
<span class="timestamp"><time>04:20 PM ET 09/28/2018</time></span>
</td>

电流输出:

('Last % Change', '\n-0.39%\n04:20 PM ET 09/28/2018\n')

期望的输出:

('Last % Change', -0.39)

标签: pythonpython-3.xbeautifulsoup

解决方案


如果目标跨度的跨度类名称始终为“负”,您可以执行以下操作:

for row in table.find_all("tr"):
    dataset = list(zip(headings, (td.find(‘span’, { “class”: “negative”} ).get_text() for td in row.find_all(“td”))))

或者,如果它并不总是“负面的”,你会发现

for row in table.find_all("tr"):
    dataset = list(zip(headings, (td.find(‘span’).get_text() for td in row.find_all(“td”))))

为了让您的程序顺利运行,请尝试捕获所有可能的错误。例如,如果找不到 td 怎么办?

现在它只会崩溃。


推荐阅读