我正在尝试使用Python从Yahoo Finance上的损益表中抓取数据。
我想提取包含在以下内容中的净收入:
import re, requests
from bs4 import BeautifulSoup
url = 'https://finance.yahoo.com/q/is?s=AAPL&annual'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
pattern = re.compile('Net Income')
title = soup.find('strong', text=pattern)
row = title.parent.parent
cells = row.find_all('td')[1:] #exclude the <td> with 'Net Income'
values = [ c.text.strip() for c in cells ]
但是我收到此错误:
您知道什么可能导致此问题吗?
您可以通过搜索'div'标签来获得净收入值。这应该可以解决问题:
import re, requests
from bs4 import BeautifulSoup
url = 'https://finance.yahoo.com/q/is?s=AAPL&annual'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
title = soup.find('div', string=re.compile('Net Income'))
row = title.parent.parent
values = [i.text for i in row]
print(values[1:])
结果:
['57,215,000', '55,256,000', '59,531,000', '48,351,000', '45,687,000']
您也可以尝试一个名为yahooquery的软件包。可以使用以下命令很简单地检索数据:
from yahooquery import Ticket
aapl = Ticker(‘aapl’)
inc = aapl.income_statement()
inc[‘NetIncome’]