python - 从 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)
解决方案
如果目标跨度的跨度类名称始终为“负”,您可以执行以下操作:
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 怎么办?
现在它只会崩溃。
推荐阅读
- amp-html - Google Pages Speed Tool 不支持 AMP 页面?
- python - 如何将滑块中的值存储为对象创建可以使用的整数
- css - MailChimp 中的中心按钮
- python - 无法从子目录导入 python 模块
- javascript - JS,如何在特定显示器上启动应用程序?
- vb.net - Visual Basic 中的简单银行应用程序
- postgresql - Docker:postgres与节点之间没有连接
- c++ - 使用 ssh 重新连接到远程 Ubuntu 机器后,如何继续使用 gdb 调试 c++ 代码?
- mysql - 如何使用我的 sql 中具有“日期格式”的列按“月份”排序?
- prolog - Prolog中列表中的重复和双倍元素