使用美丽汤和熊猫从网页获取表格



运行 Python 3.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_addr。

第二个 URL 使用 Javascript 填充表。如果您使用wget或在谷歌浏览器中查看网络标签,您将看到这是最初发送的表格(即,这就是美丽的汤所看到的(:

<div id="data-container" class="row-fluid">
<div class="span12">                    
<table class="cefconnect-table-1 daily-pricing table table-striped table-condensed" id="daily-pricing" width="100%" cellpadding="5" cellspacing="0" border="0" summary="">
<thead>
<tr>
<th class="ticker">Ticker</th>
<th class="fund-name">Fund Name</th>
<th class="strategy">Strategy</th>
<th class="closing-price">Closing<br />Price</th>
<th class="price-change">Price<br />Change</th>
<th class="nav">NAV</th>
<th class="premium-discount">Premium/<br />Discount</th>
<th class="distribution-rate">Distribution<br />Rate<sup>&dagger;</sup></th>
<th class="distribution-rate-on-nav">Distribution<br />Rate on NAV</th>
<th class="return-on-nav">1 Yr Rtn<br />on NAV</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>

然后一些Javascript填充了表格。你有两个选择,要么使用无头浏览器(如PhantomJS,Selenium,有很多选项相对容易使用(并在解析之前运行Javascript,要么尝试弄清楚如何访问页面用于添加数据的API。

我总是想提到的另一种选择是联系网站的所有者并制定安排,以更直接的方式获取数据。

最新更新