运行python3.6.1的代码
import requests
import pandas as pd
from bs4 import BeautifulSoup
# url_addr = "https://www.uspto.gov/web/offices/ac/ido/oeip/taf/mclsstc/mcls1.htm"
url_addr = "https://www.cefconnect.com/closed-end-funds-daily-pricing"
html_text = requests.get(url_addr).content
bs_obj = BeautifulSoup(html_text)
tables = bs_obj.findAll('table')
dfs = list()
for table in tables:
df = pd.read_html(str(table))[0]
dfs.append(df)
print(df)
仅获取列标题,但不获取实际数据,并提供输出
Empty DataFrame
Columns: [Ticker, Fund Name, Strategy, ClosingPrice, PriceChange, NAV, Premium/Discount, DistributionRate, DistributionRate on NAV, 1 Yr Rtnon NAV]
Index: []
它适用于被注释掉的url\u addr。你知道吗
第二个URL用Javascript填充表。如果您使用
wget
或查看Google Chrome中的网络选项卡,您将看到这是最初发送的表(即,这就是beautiful soup看到的):然后一些Javascript填充表。这里有两个选项,要么使用headless browser(像PhantomJS、Selenium,有很多相对容易使用的选项)并在解析之前运行Javascript,要么尝试找出如何访问页面用于添加数据的API。你知道吗
另一个选择,我总是喜欢提到,是联系网站的所有者,并制定一个安排,以更直接的方式获取数据。你知道吗
相关问题 更多 >
编程相关推荐