python - 如何根据 span.text 获取 td 值?
问题描述
我想从路透社收集一些资产负债表指标/值。
例如,我想获得“总资产”最近三年的价值。我能够找到相应span.text
的值,但我如何获得过去三年 2020、2019 和 2018 年的值?我知道它们存储在一个td
值中,但我不知道跳进去td
。
from bs4 import BeautifulSoup
import requests
url_balance = 'https://www.reuters.com/companies/AAPL.OQ/financials/balance-sheet-annual'
page = requests.get(url_balance)
if page.status_code == requests.codes.ok:
soup = BeautifulSoup(page.content, 'html.parser')
spans = soup.findAll('span')
for span in spans:
if span.text == 'Total Assets':
#total_asset_val_2020 = ??? How to get the value of Total Asset 2020 into that variable?
#total_asset_val_2019 = ??? How to get the value of Total Asset 2019 into that variable?
#total_asset_val_2018 = ??? How to get the value of Total Asset 2018 into that variable?
print(span.text)
解决方案
这是您可以尝试的解决方案,
from bs4 import BeautifulSoup
import requests
url_balance = 'https://www.reuters.com/companies/AAPL.OQ/financials/balance-sheet-annual'
page = requests.get(url_balance)
soup = BeautifulSoup(page.content, 'html.parser')
dates_ = ["20", "19", "18", "17", "16"]
total_assets = (
i.text for i in soup.find("span", text="Total Assets").parent.parent.find_all("td")
if i.text.strip()
)
print(list(zip(dates_, total_assets)))
[('20', '323,888.00'), ('19', '338,516.00'), ('18', '365,725.00'), ('17', '375,319.00'), ('16', '321,686.00')]
推荐阅读
- php - Laravel 8:如何将图像存储到数据库(使用正确的文件路径)并将其显示到视图中
- python - 使用 Pytest 在函数中模拟引发异常
- nest-device-access - Google Nest 摄像头扩展直播
- docker - Gitlab 到远程 docker - 持续开发
- spring-boot - Azure 工件限制为 500Mb
- c - Weird gcc warning with _Generic
- php - 是否可以像这样定义 GET 和 POST ?
- javascript - 根据文件是否存在于特定文件夹中显示项目,并根据按钮设置的内容创建/删除文件
- reactjs - React 无法将状态从一个页面传递到另一个页面
- package - 在 DevOps 中,工件和包之间有什么区别