首页 > 解决方案 > 从雅虎财务错误中抓取 Python:“NoneType”对象没有属性“父”

问题描述

我正在尝试使用 Python从Yahoo Finance的损益表中抓取数据。

我想提取包含在以下内容中的净收入:

Yahoo_Finance_Screen

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 ]

但是我收到了这个错误:

错误控制台

你知道是什么导致了这个问题吗?

标签: pythonhtmlbeautifulsoupyahoo-finance

解决方案


您可以通过搜索“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']


推荐阅读