以下代码从网页上的特定表中提取数据:
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)
答案 0 :(得分:1)
如果目标跨度的跨度类名称始终为“负”,则可以执行以下操作:
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怎么办?
现在它将崩溃。