-2

我希望从 tiingo.com 上各自的网页上抓取标准普尔 500 指数中各家公司的财务数据

例如,采用以下 URL:

https://www.tiingo.com/f/b/aapl

显示 Apple 最新的资产负债表数据

我希望提取最近一个季度的“Property, Plant & Equipment”金额,在这个特定实例中为 25.45B。但是,我无法编写正确的 Beautiful Soup 代码来提取此文本。

检查元素,我看到 25.45B 数字在元素内的类“ng-binding ng-scope”和类“col-xs-6 col-sm-3 col-md-3 col-lg-”内3 statement-field-data ng-scope”,它本身属于“col-xs-7 col-sm-8 col-md-8 col-lg-9 no-padding-left no-padding-right”类。

但是,我不确定如何准确编写 Beautiful Soup 代码来定位正确的元素,然后执行 element.getText() 函数。

我在想这样的事情:

import os, bs4, requests

res_bal = requests.get("https://www.tiingo.com/f/b/aapl")

res_bal.raise_for_status()

soup_bal = bs4.BeautifulSoup(res_bal.text, "html.parser")

elems_bal = soup_bal.select(".col-xs-6 col-sm-3 col-md-3 col-lg-3 statement-field-data ng-scope")

elems_bal_2 = elems_bal.select(".ng-binding ng-scope")

joe = elems_bal_2.getText()

print(joe)

但到目前为止,我还没有成功使用此代码。任何帮助将非常感激!

4

1 回答 1

-2

选择器的问题

elems_bal = soup_bal.select(".col-xs-6 col-sm-3 col-md-3 col-lg-3 statement-field-data ng-scope")

elems_bal_2 = elems_bal.select(".ng-binding ng-scope")

就是说,页面上存在多个具有相同类的元素,因此您没有得到正确的结果。

请注意,如果您仅使用 beautifulsoup 和 request,则页面源中的内容没有您想要抓取的数据,这可以在 selenium 和 beautifulsoup 的帮助下完成,您可以这样做:如果您没有 selenium,请先安装:pip install selenium

这是相同的工作代码:

from selenium import webdriver
import  bs4, time

driver = webdriver.Firefox()   
driver.get("https://www.tiingo.com/f/b/aapl")
driver.maximize_window()
# sleep is given so that JS populate data in this time
time.sleep(10)
pSource= driver.page_source

soup = bs4.BeautifulSoup(pSource, "html.parser")

Property=soup.findAll('div',{'class':'col-xs-5 col-sm-4 col-md-4 col-lg-3 statement-field-name indent-2'})
for P in Property:
    if 'Property' in P.text.strip():
        print P.text

x=soup.find("a",{"ng-click":"toggleFundData('Property, Plant & Equipment',SDCol.restatedString==='restated',true)"})
print x.text

相同的输出是:

Property, Plant & Equipment
25.45B
于 2016-08-21T12:05:31.497 回答