所以我在 Python for Finance 上使用这个 series,它一直给我错误 --
1) line 22, in <module> save_sp500_tickers() and
2) line 8, in save_sp500_tickers
soup = bs.BeautifulSoup(resp.text,'lxml')and
3) line 165, in __init__
% ",".join(features))
bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml.
Do you need to install a parser library?
我已经做了一整天了,老实说我拒绝放弃,对此的任何帮助都将不胜感激。另外,如果有人对 pickle 以外的东西有任何建议,并且可以帮助写一些让我可以在没有 pickle 的情况下调用 SP500 的东西,那就太好了。
import bs4 as bs
import pickle
import requests
import lxml
def save_sp500_tickers():
resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup = bs.BeautifulSoup(resp.text,'lxml')
table = soup.find('table', {'class': 'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[0].text
tickers.append(ticker)
with open("sp500tickers.pickle", "wb") as f:
pickle.dump(tickers, f)
print(tickers)
return tickers
save_sp500_tickers()
在我的系统上按原样运行代码。可能,正如 Eric 所建议的,您应该安装 lxml。
不幸的是,如果你在 Windows 上
pip install lxml
不起作用,除非你有一个完整的编译器基础设施设置,而你可能没有。
幸运的是,您可以从 http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml 获得预编译的二进制安装程序 - 确保选择与您的 python 版本匹配的版本,无论它是 32 还是64 位。
编辑:只是出于兴趣,尝试更改行
soup = bs.BeautifulSoup(resp.text, 'html.parser') # use Python's built-in parser instead
有关可用解析器的列表,请参阅https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser。
pandas.read_html
。还需要像 lxml
或 bs4
+html5lib
这样的解析器,因为它由 pandas
在内部使用。
import pandas as pd
def list_sp500() -> pd.DataFrame:
# Ref: https://stackoverflow.com/a/75845569/
url = 'https://en.m.wikipedia.org/wiki/List_of_S%26P_500_companies'
return pd.read_html(url, attrs={'id': 'constituents'}, index_col='Symbol')[0]
用法:
>> df = list_sp500()
>> df.head()
Security GICS Sector ... CIK Founded
Symbol ...
MMM 3M Industrials ... 66740 1902
AOS A. O. Smith Industrials ... 91142 1916
ABT Abbott Health Care ... 1800 1888
ABBV AbbVie Health Care ... 1551152 2013 (1888)
ACN Accenture Information Technology ... 1467373 1989
[5 rows x 7 columns]
>> symbols = df.index.to_list()
>> symbols[:5]
['MMM', 'AOS', 'ABT', 'ABBV', 'ACN']
这是用 Pandas 1.5.3 测试的。