【发布时间】:2017-02-21 08:14:27
【问题描述】:
我正在使用 beautifulsoup4 来获取股票数据并发送到 Python 中的电子表格。我遇到的问题是我无法让我的循环跳过返回 None 的属性。所以我需要的是将空值添加到行的代码 属性将返回无。
//my dictionay for storing data
data = {
'Fiscal Quarter End' : [],
'Date Reported' : [],
'Earnings Per Share' : [],
'Consensus EPS* Forecast' : [],
'% Surprise' : []
}
url = ""
html = requests.get(url)
data = html.text
soup = bs4.BeautifulSoup(data)
table = soup.find("div", class_="genTable")
for row in table.find_all('tr')[1:]:
if row.has_attr('tr'):
cols = row.find_all("td")
data['Fiscal Quarter End'].append( cols[0].get_text() )
data['Date Reported'].append( cols[1].get_text() )
data['Earnings Per Share'].append( cols[2].get_text() )
data['Consensus EPS* Forecast'].append( cols[3].get_text() )
data['% Surprise'].append( cols[4].get_text() )
else:
//where i need to add in the empty 'n/a' values
data['Fiscal Quarter End'].append()
data['Date Reported'].append()
data['Earnings Per Share'].append()
data['Consensus EPS* Forecast'].append()
data['% Surprise'].append()
【问题讨论】:
-
//不是 Python 中的注释... -
您正在定义一个名为 data 的字典,然后将 html.text 分配给 data,然后期望 data 成为字典。
-
您首先将 data 变量用作字典,然后将其用作存储 HTML 文本的字符串。这肯定会给你带来麻烦。您能否解释一下为什么需要添加“空”数据?
-
如果 find_all 返回空,我希望行为空。我需要将那些空行放入字典中。
标签: python csv dictionary beautifulsoup nonetype