我想提高treasury.gov网站上提供的每一笔国债收益率。
我如何获取这些信息?我假设我必须使用BeautifulSoup或Selenium或类似的东西(最好是BS4)。我最终想把这些数据放在Pandas DataFrame中。
答案 0 :(得分:2)
这是使用requests和beautifulsoup
获取表格中数据的一种方法import pandas as pd
import requests
from bs4 import BeautifulSoup
url = 'https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yieldAll'
r = requests.get(url)
html = r.text
soup = BeautifulSoup(html)
table = soup.find('table', {"class": "t-chart"})
rows = table.find_all('tr')
data = []
for row in rows[1:]:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele])
result = pd.DataFrame(data, columns=['Date', '1 Mo', '3 Mo', '6 Mo', '1 Yr', '2 Yr', '3 Yr', '5 Yr', '7 Yr', '10 Yr', '20 Yr', '30 Yr'])
print(result)